LeetCode 144 二叉树的前序遍历

LeetCode 144 二叉树的前序遍历

问题描述
给定一个二叉树,返回它的 前序 遍历。

迭代法

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:36.4 MB, 在所有 Java 提交中击败了98.91%的用户

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        //迭代实现前序遍历
        List<TreeNode> stack = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
        while(!stack.isEmpty() || root!=null) {
            if(root!=null) {
                if(root.right!=null) {
                    stack.add(root.right);
                }
                ans.add(root.val);
                root = root.left;
            }
            else {
                root = stack.get(stack.size()-1);
                stack.remove(stack.size()-1);
            }
        }

        return ans;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13882698.html