题目:
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?
解题思路:前序遍历的迭代方式。
c++版本:
class Solution {
public:
void visitAlongLeft(TreeNode* x,stack<TreeNode*>&s,vector<int>& res){
while(x){
res.push_back(x->val);
s.push(x->right);
x = x->left;
}
}
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> res;
//TreeNode *x = root;
while(true){
visitAlongLeft(root,s,res);
if(s.empty())
break;
root = s.top();s.pop();
}
return res;
}
};
python版本:
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def visitAlongLeft(x,s,res):
while(x!=None):
res.append(x.val)
s.append(x)
x = x.left
s,res = [], []
while True:
visitAlongLeft(root,s,res)
if(len(s)==0):break
root = s.pop()
root = root.right
return res