Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的统一迭代法 建议 #595

Closed
zhangdanfenggg opened this issue Aug 12, 2021 · 0 comments
Closed

二叉树的统一迭代法 建议 #595

zhangdanfenggg opened this issue Aug 12, 2021 · 0 comments

Comments

@zhangdanfenggg
Copy link

zhangdanfenggg commented Aug 12, 2021

完全没有必要将null添加到栈中,因为执行过if中的语句后,下一次循环必然执行else中的语句。
所以可以将代码放到一次循环中。

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root==null) return res;
        Deque<TreeNode> deque = new LinkedList<>();
        TreeNode cur = root;
        deque.push(cur);
        while (!deque.isEmpty()){
            cur = deque.peek();
            if (cur!=null){
                deque.pop();
                if (cur.right!=null) deque.push(cur.right);
                if (cur.left!=null) deque.push(cur.left);
                deque.push(cur);
                cur = deque.peek();
                deque.pop();
                if (cur != null) res.add(cur.val);
            }
        }
        return res;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant