在二叉树中打印所有根到叶子路径

编程入门 行业动态 更新时间:2024-10-21 15:47:04
本文介绍了在二叉树中打印所有根到叶子路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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.

更多推荐

在二叉树中打印所有根到叶子路径

本文发布于:2023-11-30 04:16:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648689.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   叶子   二叉树

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!