題目:
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?
分析:
二叉樹的先序遍歷順序爲中左右。非遞歸時,根節點首先進行訪問,這時需要記錄它的左右孩子情況,而左孩子先訪問,因此用一個棧來記錄右孩子,先把右孩子壓入棧,然後再壓入左孩子。
Java代碼實現:
/**
* Definition for a binary tree node.
* 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> result = new ArrayList<Integer>();
if(root==null)
return result;
Stack<TreeNode> s = new Stack<TreeNode>();
s.push(root);
while(!s.isEmpty())
{
TreeNode node = s.pop();
result.add(node.val);
if(node.right!=null)
s.push(node.right);
if(node.left!=null)
s.push(node.left);
}
return result;
}
}