print all root to leaf paths in a binary tree

后端 未结 12 1375
野性不改
野性不改 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:45

    Here is my solution: Once we traverse the left or right path just remove the last element.

    Code:

    public static void printPath(TreeNode root, ArrayList list) {
    
        if(root==null)
            return;
    
        list.add(root.data);
    
        if(root.left==null && root.right==null) {
            System.out.println(list);
            return;
        }
        else {
            printPath(root.left,list);
            list.remove(list.size()-1);
    
            printPath(root.right,list);
            list.remove(list.size()-1);
    
        }
    }
    

提交回复
热议问题