Problem : 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.C++版
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
TreeNode* p = root,*q = root;
vector<int> result;
stack<TreeNode*> stack;
while(NULL != p || !stack.empty()){
while(NULL != p){
result.push_back(p->val);
stack.push(p);
p = p->left;
}
if(!stack.empty()){
q = stack.top();
stack.pop();
p = q->right;
}
}
return result;
}
};
2.Java版
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
TreeNode p = root,q = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
while(null != p || !stack.isEmpty()){
while(null != p){
result.add(p.val);
stack.push(p);
p = p.left;
}
if(!stack.isEmpty()){
q = stack.pop();
p = q.right;
}
}
return result;
}
}
3.Python版
待续
完