给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*> rights;
vector<int> results;
TreeNode* current = root;
while(current != NULL) {
results.push_back(current->val);
if(current->left!=NULL) {
if(current->right!=NULL) rights.push(current->right);
current = current->left;
} else if(current->right!=NULL) {
current = current->right;
} else if(rights.size()>0) {
current = rights.top();
rights.pop();
} else {
current = NULL;
}
}
return results;
}
};