您的位置:首页 > 其它

【LeetCode】-Binary Tree Preorder Traversal

2014-09-22 16:10 281 查看
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]
.

/**

 * 二叉树前序遍历的非递归实现:

 * 

 * 相比后续遍历的非递归实现,前序遍历要简单很多了

 * 

 * Definition for binary tree

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

    public List<Integer> preorderTraversal(TreeNode root) {

         List<Integer> list = new ArrayList<Integer>();
if( root==null )
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while( p!=null || !stack.isEmpty() ){
while( p!=null ){
list.add(p.val);
stack.push(p);

p = p.left;
 
}
if( !stack.isEmpty() ){
p = stack.pop();
p = p.right;
}
}
return list;    

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: