题目描述:
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> result;
if(root==NULL) return result;
stack<TreeNode*> s;
TreeNode* p=root;
while(p!=NULL||!s.empty())
{
if(p!=NULL)
{
result.push_back(p->val);
s.push(p);
p=p->left;
}
else
{
p=s.top()->right;
s.pop();
}
}
return result;
}
};