print all root to leaf paths in a binary tree

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

    We can use recursion to achieve it. Right data structure makes it concise and efficient.

    List> printPath(Tree root){
    
        if(root==null)return null;
    
        List> leftPath= printPath(root.left);
        List> rightPath= printPath(root.right);
    
        for(LinkedList t: leftPath){
             t.addFirst(root);
        }
        for(LinkedList t: rightPath){
             t.addFirst(root);
        }
    
    
     leftPath.addAll(rightPath);
    
     return leftPath;
    
    
    }
    

提交回复
热议问题