Binary Tree Preorder Traversal

来源:互联网 发布:管家婆erp软件 编辑:程序博客网 时间:2024/05/22 17:47

题目:Given a binary tree, return the preorder traversal of its nodes' values.

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

非递归先序遍历一棵二叉树

之前遇到都是写的递归式的,觉得迭代方式不好理解,然后在discuss里看到一句解释 Just remember to push the right child and then the left child, which makes the left one come out first.  觉得就好理解的多了

public List<Integer> preorderTraversal(TreeNode root) {        List<Integer> list = new ArrayList<Integer>();        if (root == null) {        return list;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        stack.push(root);        while (!stack.isEmpty()) {        TreeNode node = stack.pop();        list.add(node.val);        if (node.right != null) {        stack.push(node.right);        }        if (node.left != null) {        stack.push(node.left);        }        }        return list;}


0 0
原创粉丝点击