栈-N144-二叉树的前序遍历

2019-03-30  本文已影响0人  三次元蚂蚁

题目

思路

  1. 栈顶元素有右孩子,将右孩子入栈
  2. 栈顶元素有左孩子,将左孩子入栈

代码

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode top;
        stack.push(root);
        while (!stack.isEmpty()) {
            top = stack.pop();
            result.add(top.val);
            if (top.right != null) {
                stack.push(top.right);
            }
            if (top.left != null) {
                stack.push(top.left);
            }
        }
        return result;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读