3

当我第一次解决二叉树后序遍历的问题时,我只使用一个堆栈来存储节点,并使用一个列表作为结果。所以时间复杂度显然是N^2。但是如果使用 2 个堆栈,时间复杂度可以简化为 N。

至于前序遍历,我认为使用一个堆栈就足够了。但我的解决方案运行时间仍然停留在中级水平。

那么有没有什么办法可以改善呢?下面是我的代码:

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {

        Stack<TreeNode> nodes = new Stack<TreeNode>();
        ArrayList<Integer> result = new ArrayList<Integer>();

        if (root == null)
            return result;
        nodes.push(root);

        while (!nodes.isEmpty()) {
            TreeNode temp = nodes.pop();
            result.add(temp.val);

            if (temp.right != null) {
                nodes.push(temp.right);
            }
            if (temp.left != null) {
                nodes.push(temp.left);
            }
        }

        return result;
    }
}

谢谢!

4

0 回答 0