print all root to leaf paths in a binary tree

后端 未结 12 1357
野性不改
野性不改 2020-12-23 14:55

i am trying to print all root to leaf paths in a binary tree using java.

public void printAllRootToLeafPaths(Node node,ArrayList path) 
{
    if(node==null)         


        
相关标签:
12条回答
  • 2020-12-23 15:30
    public void PrintAllPossiblePath(Node node,List<Node> nodelist)
    {
        if(node != null)
        {
                nodelist.add(node);
                if(node.left != null)
                {
                    PrintAllPossiblePath(node.left,nodelist);
                }
                if(node.right != null)
                {
                    PrintAllPossiblePath(node.right,nodelist);
                }
                else if(node.left == null && node.right == null)
                {
    
                for(int i=0;i<nodelist.size();i++)
                {
                    System.out.print(nodelist.get(i)._Value);
                }
                System.out.println();
                }
                nodelist.remove(node);
        }
    }
    

    nodelist.remove(node) is the key, it removes the element once it prints the respective path

    0 讨论(0)
  • 2020-12-23 15:36

    You're passing your list along recursively, but that is a mutable object, so all the calls will modify it (by calling List.add) and mangle your results. Try cloning / copying the path argument to all the recursive calls to provide each branch (harhar) with its own context.

    0 讨论(0)
  • 2020-12-23 15:37

    This is my solution for storing all path values in List and then just print the list

    Basically what code is recursively calling rootToLeafPaths method and passing the string on values separated by comma (","). The base condition for recursive function is when we reach leaf node (both children are null). At that time, we are just extracting int values from string and storing it in List

    class Solution {
        public void printBTfromRootToLeaf (TreeNode root) {
            if(root == null) return 0;
            if (root.left == null & root.right == null) return 1;
            List<List<Integer>> res = new ArrayList();
            rootToLeafPaths(root, res, "");
            System.out.println(res);
        }
    private void rootToLeafPaths(TreeNode root, List<List<Integer>> res, String curr) {
            if (root.left == null && root.right == null) {
                String[] vals = curr.split(",");
                List<Integer> temp = new ArrayList<>();
                for (String val : vals) temp.add(Integer.parseInt(val));
                temp.add(root.val);
                res.add(new ArrayList<>(temp));
            }
            if (root.left != null) rootToLeafPaths(root.left, res, curr + root.val + ",");
            if (root.right != null) rootToLeafPaths(root.right, res, curr + root.val + ",");
        }
    }
    
    0 讨论(0)
  • 2020-12-23 15:40

    you can do this way also. here is my Java code.

    public void printPaths(Node r,ArrayList arr)
    {
        if(r==null)
        {
            return;
        }
        arr.add(r.data);
        if(r.left==null && r.right==null)
        {
            printlnArray(arr);
        }
        else
        {
            printPaths(r.left,arr);
            printPaths(r.right,arr);
        }
    
         arr.remove(arr.size()-1);
    }
    
    0 讨论(0)
  • 2020-12-23 15:41

    Here is the correct Implementation

    public static <T extends Comparable<? super T>> List<List<T>> printAllPaths(BinaryTreeNode<T> node) {
        List <List<T>> paths = new ArrayList<List<T>>();
        doPrintAllPaths(node, paths, new ArrayList<T>());
        return paths;
    }
    
    private static <T extends Comparable<? super T>> void doPrintAllPaths(BinaryTreeNode<T> node, List<List<T>> allPaths, List<T> path) {
        if (node == null) {
            return ;
        }
        path.add(node.getData());
        if (node.isLeafNode()) {
            allPaths.add(new ArrayList<T>(path));   
    
        } else {
            doPrintAllPaths(node.getLeft(), allPaths, path);
            doPrintAllPaths(node.getRight(), allPaths, path);
        }
        path.remove(node.getData());
    }
    

    Here is the test case

    @Test
    public void printAllPaths() {
        BinaryTreeNode<Integer> bt = BinaryTreeUtil.<Integer>fromInAndPostOrder(new Integer[]{4,2,5,6,1,7,3}, new Integer[]{4,6,5,2,7,3,1});
        List <List<Integer>> paths = BinaryTreeUtil.printAllPaths(bt);
    
        assertThat(paths.get(0).toArray(new Integer[0]), equalTo(new Integer[]{1, 2, 4}));
        assertThat(paths.get(1).toArray(new Integer[0]), equalTo(new Integer[]{1, 2, 5, 6}));
        assertThat(paths.get(2).toArray(new Integer[0]), equalTo(new Integer[]{1, 3, 7}));
    
        for (List<Integer> list : paths) {          
            for (Integer integer : list) {
                System.out.print(String.format(" %d", integer));
            }
            System.out.println();
        }
    }
    

    Here is the output

    1 2 4
    
    1 2 5 6
    
    1 3 7
    
    0 讨论(0)
  • 2020-12-23 15:41

    It is written with JS but You can gain the logic.

    function dive(t, res, arr) {
            if(t.value != null && t.value != undefined) {
                res = res ? `${res}->${t.value}`: `${t.value}`;
            }
            if(t.left) {
                dive(t.left, res, arr );
            } 
            if(t.right) {
                dive(t.right, res, arr );
            } 
            if(!t.left && !t.right) {
                console.log(res)
                arr.push(res);
                return;
            }
    }
    
    function getPaths(t) {
        let arr = [];
        if(!t.left && !t.right) {
            t.value != null && t.value != undefined && arr.push(`${t.value}`);
            console.log(arr)
            return arr;
        }
        dive(t, null, arr);
        console.log(arr)
    }
    
    
    //INPUT
    const x = {
        value: 5,
        left: {
            value: 4,
            left: {
                value: 3,
                left: {
                    value: 2,
                    left: {
                        value: 1,
                        left: {
                            value: 0
                        },
                        right: {
                            value: 1.5
                        }
                    },
                    right: {
                        value: 2.5
                    }
                },
                right: {
                    value: 3.5
                }
            },
            right: {
                value: 4.5,
                right: {
                    value: 4.8
                }
            }
        },
        right: {
            value: 8,
            left: {
                value: 7
            }
        }
    }
    
    getPaths(x);
    
    //OUTPUT
    
    [ '5->4->3->2->1->0',
      '5->4->3->2->1->1.5',
      '5->4->3->2->2.5',
      '5->4->3->3.5',
      '5->4->4.5->4.8',
      '5->8->7' ]
    
    
    0 讨论(0)
提交回复
热议问题