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?

如果不能使用recursive 那么就只能使用stack来保存状态。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public ArrayList<Integer> preorderTraversal(TreeNode root) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         Stack<TreeNode> st = new Stack<TreeNode>();
15         ArrayList<Integer> result = new ArrayList<Integer>();
16         if(root == null) return result;
17         st.push(root);
18         while(!st.isEmpty()){
19             TreeNode tmp = st.pop();
20             result.add(tmp.val);
21             if(tmp.right != null) st.push(tmp.right);
22             if(tmp.left != null) st.push(tmp.left);
23         }
24         return result;
25     }
26 }

注意要现存right,再存left,这样才能保证先expand的是left。

posted on 2013-11-26 13:05  Step-BY-Step  阅读(188)  评论(0编辑  收藏  举报

导航