简体   繁体   中英

Having trouble printing root to leaf paths for binary tree

I am trying to print all the root to leaf paths for a binary tree and I need to return the result as a List of Strings. I am trying to use recursion and StringBuilders to do this but with each new path, instead of removing the old path, it is appending to it.

If the paths from root to leaf are 5->3->2->1, 5->3->4, 5->7->6 and 5->7->8 (the example I am using), my result is coming as the following:

5->3->2->1

5->3->2->14

5->3->2->147->6

5->3->2->147->68

This is because of the way I am using StringBuilder but I am not able to figure out what I am doing wrong. Following is my entire code. Any help would be appreciated:

public class solution{
    static List<String> allPaths = new ArrayList<String>();
    public static List<String> binaryTreePaths (BinaryTree bT){
        StringBuilder sb = new StringBuilder();
        binaryTreePathsHelper(bT, sb);
        return allPaths;
    }

    public static void binaryTreePathsHelper(BinaryTree bT, StringBuilder sb){
        if (bT == null){
            return;
        }
        if (bT.getLeftChild() == null && bT.getRightChild() == null){
            sb.append(bT.getRoot() + "");
            allPaths.add(sb.toString());
            sb = new StringBuilder();
        }
        else{
            sb.append(bT.getRoot() + "->");
        }
        if (bT.getLeftChild() != null){
            binaryTreePathsHelper(bT.getLeftChild(), sb);
        }
        if (bT.getRightChild() != null){
            binaryTreePathsHelper(bT.getRightChild(), sb);
        }
    }
}

The problem happens when your tree has two paths from the current node. You're passing the same instance of StringBuilder into both instances of binaryTreePathsHelper . Which means that both paths are ending up in a single string builder.

The easiest solution is to not pass StringBuilder around. Instead, pass String around. Then you'll be creating new String s each time you append to your passed-in String , eliminating the possibility of accidental object reuse.

If you really want to pass around instances of StringBuilder , you need to duplicate them when you recursively call binaryTreePathsHelper . For example:

binaryTreePathsHelper(bT.getRightChild(), new StringBuilder(sb.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM