【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
return
/**
* 二叉树前序遍历的非递归实现:
*
* 相比后续遍历的非递归实现,前序遍历要简单很多了
*
* 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;
}
}
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;
}
}
相关文章推荐
- LeetCode----Binary Tree Preorder Traversal
- LeetCode---Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode | Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- leetcode-105&106 Construct Binary Tree from Preorder and Inorder Traversal I&II
- 【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode][Java] Binary Tree Preorder Traversal
- LEETCODE: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Binary Tree Preorder Traversal
- LeetCode之Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Binary Tree Preorder Traversal
- 【Leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Binary Tree Preorder Traversal
- LeetCode --- 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal [105]
- leetcode-Construct Binary Tree from Preorder and Inorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]144 Binary Tree Preorder Traversal