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

*Binary Tree Preorder Traversal

时间:2015-08-07 10:56:38      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

题目

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 public class Solution {
 2     public List<Integer> preorderTraversal(TreeNode root) 
 3     {
 4         List<Integer> result = new ArrayList<Integer> ();
 5         LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
 6         
 7         while(root!=null||stack.isEmpty()==false)
 8         {
 9             if(root!=null)
10             {
11                 result.add(root.val);
12                 stack.push(root);
13                 root=root.left;
14             }
15             else
16             {
17                 root=stack.pop();
18                 root=root.right;
19                 
20             }
21         }
22         
23         return result;
24     }
25 }

 

*Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4709987.html

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