144. Binary Tree Preorder Traversal

题目:

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?

链接:https://leetcode.com/problems/binary-tree-preorder-traversal/#/description

5/10/2017

 1 public class Solution {
 2     public List<Integer> preorderTraversal(TreeNode root) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         if (root == null) return ret;
 5 
 6         Stack<TreeNode> stack = new Stack<TreeNode>();
 7         TreeNode current;
 8         stack.push(root);
 9         while (!stack.empty()) {
10             current = stack.pop();
11             if (current.right != null) {
12                 stack.push(current.right);
13             }
14             if (current.left != null) {
15                 stack.push(current.left);
16             }
17             ret.add(current.val);
18         }
19         return current;
20     }
21 }

更多讨论

https://discuss.leetcode.com/category/152/binary-tree-preorder-traversal

需要再看morris traversal

posted @ 2017-05-11 05:25  panini  阅读(125)  评论(0编辑  收藏  举报