[英]Node to root path in Binary Tree
I was trying to find the node to root path in a binary tree using Leap Of Faith but I'm stuck now.我试图使用 Leap Of Faith 在二叉树中找到根路径的节点,但我现在卡住了。
It works in some simple cases, but it returns the wrong path for other cases.它在一些简单的情况下有效,但在其他情况下返回错误的路径。
For example, for this tree:例如,对于这棵树:
1
/ \
2 3
...and passing 3 as argument, it returns {1, 2} when {1, 3} is expected. ...并将 3 作为参数传递,当需要 {1, 3} 时,它返回 {1, 2}。
Can anyone tell me what is wrong with my code?谁能告诉我我的代码有什么问题?
public static ArrayList<Integer> nodeToRootPath(Node root, int data) {
// write your code here
ArrayList<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
if (root.data == data) {
res.add(data);
return res;
}
res = nodeToRootPath(root.left, data);
if (res.size() != 0) {
res.add(root.data);
return res;
}
else {
res.clear();
res = nodeToRootPath(root.right, data);
res.add(root.data);
return res;
}
}
The problem is that when the recursion comes back from the right
subtree, your code does not verify whether that search was successful.问题是当递归
right
子树返回时,您的代码不会验证该搜索是否成功。 It should -- just like for the left-side -- check whether res.size()
is non-zero before adding anything to it.它应该 - 就像左侧一样 - 在
res.size()
添加任何内容之前检查res.size()
是否为非零。
Some side notes:一些旁注:
res.clear()
when you are going to assign a new value to res
in the next line.res
分配新值时,没有必要调用res.clear()
。 Here is a correction:这是一个更正:
public static ArrayList<Integer> nodeToRootPath(Node root, int data) {
if (root == null) {
return new ArrayList<>();
}
if (root.data == data) {
return new ArrayList<>(Arrays.asList(data));
}
ArrayList<Integer> res = nodeToRootPath(root.left, data);
if (res.size() == 0) {
res = nodeToRootPath(root.right, data);
}
if (res.size() != 0) {
res.add(root.data);
}
return res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.