码迷,mamicode.com
首页 > 其他好文 > 详细

[leecode]Binary Tree Preorder Traversal

时间:2014-08-31 18:34:41      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   strong   ar   for   

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?

算法思路:

思路1:递归版

代码如下:

 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     List<Integer> res = new ArrayList<Integer>();
12     public List<Integer> preorderTraversal(TreeNode root) {
13         if(root == null) return res;
14         res.add(root.val);
15         if(root.left != null) preorderTraversal(root.left);
16         if(root.right != null) preorderTraversal(root.right);
17         return res;
18     }
19 }

2. 非递归实现:

借助栈,每一次弹栈处理栈顶元素之后都将右节点、左节点分别压栈,大家画个图就明白了

代码如下:

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

 

[leecode]Binary Tree Preorder Traversal

标签:des   style   blog   http   color   io   strong   ar   for   

原文地址:http://www.cnblogs.com/huntfor/p/3947945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!