print all root to leaf paths in a binary tree

后端 未结 12 1392
野性不改
野性不改 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: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> res = new ArrayList();
            rootToLeafPaths(root, res, "");
            System.out.println(res);
        }
    private void rootToLeafPaths(TreeNode root, List> res, String curr) {
            if (root.left == null && root.right == null) {
                String[] vals = curr.split(",");
                List 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 + ",");
        }
    }
    

提交回复
热议问题