Print all paths from root to leaf in a Binary tree

后端 未结 5 1684
佛祖请我去吃肉
佛祖请我去吃肉 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 17:57

    The question here is how did you get the solution rather than did you get the solution. The performance is the key here. Create a tree object first..

    class Node {
    
    public Node left;
    public Node right;
    public Character val;
    
    public Node(char val) {
        this.val = val;
    }   
    

    get all paths in list..

    public List> printPath(Node root) {
    
        if (root == null) return new ArrayList>();
    
        List> left = printPath(root.left);
        List> right = printPath(root.right);
    
        left.addAll(right);
    
        for (LinkedList lst : left) {
            lst.addFirst(root);
        }
        if(left.size()==0){
            LinkedList lst= new LinkedList();
            lst.add(root);
            left.add(lst);
        }
        return left;
    
    }
    

    print all the paths now..

      Node root = new Node('a');
        System.out.println(root.val);
        root.left = new Node('b');
        root.left.left = new Node('c');
        root.left.right = new Node('d');
        root.right = new Node('e');
        root.right.left = new Node('f');
        root.right.right = new Node('g');
        root.right.right.left = new Node('h');
    
        List> allPaths = wc.printPath(root);
    
        for (LinkedList lst : allPaths) {
            for (Node node : lst)
                System.out.print(node.val==null ? "-" : node.val);
            System.out.println();
        }
    

提交回复
热议问题