简体   繁体   English

为什么我的预序遍历返回一个空列表?

[英]Why is my preorder traversal returning an empty list?

I am trying to understand why code is returning an empty list.我试图理解为什么代码返回一个空列表。 I am not looking for a solution to the problem.我不是在寻找问题的解决方案。 The solution already exists in What is wrong with my Preorder traversal?解决方案已经存在于我的 Preorder 遍历出了什么问题?

I want to understand, what is incorrect about my current understanding of recursion and the call stack upon using a global variable.我想了解,我目前对递归和使用全局变量的调用堆栈的理解有什么不正确。

class Solution {
    ArrayList<Integer> list;
    public List<Integer> preorderTraversal(TreeNode root) {
        list = new ArrayList<Integer>();
        preOrder(root);
        return list;
    }
    public void preOrder(TreeNode node){
        System.out.println(list.toString());
        if(node == null)
            return;
        
        list.add(node.val);
        
        //System.out.println(list.toString());
        
        preorderTraversal(node.left);
        preorderTraversal(node.right);
    }
}

For the following tree : [1,null,2,3]对于以下树: [1,null,2,3]

I notice that in the first print call I get 7 empty lists我注意到在第一次打印调用中我得到 7 个空列表

[]
[]
[]
[]
[]
[]
[]

In my second print call, I get the following在我的第二个打印电话中,我得到以下信息

[1]
[2]
[3]

Why isn't my global variable list not "saving" or "appending" to the next call stack?为什么我的全局变量列表没有“保存”或“附加”到下一个调用堆栈? It seems like, there are multiple list objects being utilized.似乎有多个列表对象正在被利用。

Because you use preorderTraversal with left and right nodes so each time it will override list value with a new empty list, you should use preOrder with left and right node like this因为您将preorderTraversal与左右节点一起使用,所以每次它将用新的空列表覆盖列表值时,您应该像这样将 preOrder 与左右节点一起使用

public void preOrder(TreeNode node){
    if(node == null)
        return;
        
    list.add(node.val);
        
    preOrder(node.left);
    preOrder(node.right);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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