LeetCode 144 Binary Tree Preorder Traversal

来源:互联网 发布:无网络csgo局域网联机 编辑:程序博客网 时间:2024/06/08 10:48

题目描述

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

1 \  2 /3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

分析

二叉树的前序遍历,题目要求用迭代,非递归方法。用栈存储结点,入栈即打印,然后按照左结点、右结点的顺序入栈。

代码

    public static List<Integer> preorderTraversal(TreeNode root) {        List<Integer> rt = new ArrayList<Integer>();        if (root == null) {            return rt;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode p = root;        while (p != null || !stack.empty()) {            while (p != null) {                rt.add(p.val);                stack.push(p);                p = p.left;            }            if (!stack.empty()) {                p = stack.pop();                p = p.right;            }        }        return rt;    }
1 0
原创粉丝点击