简体   繁体   English

二叉树中节点到根路径

[英]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:一些旁注:

  • It is not necessary to call res.clear() when you are going to assign a new value to res in the next line.当您要在下一行中为res分配新值时,没有必要调用res.clear()
  • It is pity to create a new list when eventually you are not in a base case and ignore that created new list and instead use the list you get back from a recursive call.遗憾的是,当最终您不在基本情况下时创建一个新列表并忽略该创建的新列表,而是使用从递归调用中返回的列表。 So only create a new list when you know you are in a base case.因此,仅当您知道自己处于基本情况时才创建新列表。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM