Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
大意:树的前序遍历
方法:这里只写非递归算法(可以看做一个模板,太多的题目可以套用。。。)
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode *p = root;
while (!s.empty() || p) {
if (p) {
s.push(p);
res.push_back(p->val);
p = p->left;
} else {
TreeNode *t = s.top(); s.pop();
p = t->right;
}
}
return res;
}
};