【LeetCode】-Binary Tree Preorder Traversal

来源:互联网 发布:淘宝涛哥电玩店 编辑:程序博客网 时间:2024/05/17 06:35

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;    
    }
}

0 0