Print all paths from root to leaf in a Binary tree

后端 未结 5 1682
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 17:27

Here is the code I wrote to print all paths of a Binary tree from root to leaf:

public static void printRootToLeaf(Node1 root, List list) {
           


        
5条回答
  •  隐瞒了意图╮
    2021-01-06 18:11

    If you have the reference to parent node, following code can print the paths:

    public void printPaths(Node n) {
        if(n != null) {
            if(n.left == null && n.right == null) { // found a leaf node, go up the tree
                StringBuilder sb = new StringBuilder();
                sb.append(" ").append(n);
                Node p = n.parent;
                while(p != null) {
                    sb.insert(0, " ").insert(1,p);
                    p = p.parent;
                }
                System.out.println(sb);
            }
            printPaths(n.left);
            printPaths(n.right);
        }
    }
    

提交回复
热议问题