打印二叉树中的所有根到叶路径
2022-09-02 19:15:46
						我正在尝试使用java在二叉树中打印所有根到叶路径。
public void printAllRootToLeafPaths(Node node,ArrayList path) 
{
    if(node==null)
    {
        return;
    }
    path.add(node.data);
    if(node.left==null && node.right==null)
    {
        System.out.println(path);
        return;
    }
    else
    {
        printAllRootToLeafPaths(node.left,path);
        printAllRootToLeafPaths(node.right,path);
    }      
}
在主要方法中:
 bst.printAllRootToLeafPaths(root, new ArrayList());
但它给出了错误的输出。
给定树:
   5
  / \
 /   \
1     8
 \    /\
  \  /  \
  3  6   9
预期输出:
[5, 1, 3]
[5, 8, 6]
[5, 8, 9]
但输出产生:
[5, 1, 3]
[5, 1, 3, 8, 6]
[5, 1, 3, 8, 6, 9]
有人能弄清楚吗...
 
					 
				 
				    		 
				    		 
				    		 
				    		