在二叉树中打印所有根到叶子路径 [英] print all root to leaf paths in a binary tree

查看:230
本文介绍了在二叉树中打印所有根到叶子路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用java在二叉树中打印所有根到叶子路径。

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)
    {
        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]

[5,1,3,8,6,9]

[5, 1, 3, 8, 6, 9]

可以算出来......

Can some one figure it out...

推荐答案

用以下方法调用递归方法:

Call the recursive methods with:

printAllRootToLeafPaths(node.left, new ArrayList(path));
printAllRootToLeafPaths(node.right, new ArrayList(path));

当你传递路径时会发生什么 (而不是 new ArrayList(path)是你在所有方法调用中使用单个对象,这意味着当你返回原始调用者时,该对象不在与原来相同的状态。

What happens there when you pass the path (instead of new ArrayList(path) is that you use a single object in all methods call, which means that, when you return to the original caller, the object is not in the same state as it was.

您只需要创建一个新对象并将其初始化为原始值。这样原始对象就不会被修改。

You just need to create a new object and initialize it to the original values. This way the original object does not get modified.

这篇关于在二叉树中打印所有根到叶子路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆