首页 > 其他 > 详细

*Binary Tree Preorder Traversal

时间:2015-08-07 10:53:28      阅读:125      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!