leetcode 144. 二叉树的前序遍历(Binary Tree Preorder Traversal)
题目描述:
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解法:
#define PR pair<TreeNode*, int> // node and its state
/**
* 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:
void inOrder(TreeNode* root, vector<int>& res){
if(root != NULL){
res.push_back(root->val);
inOrder(root->left, res);
inOrder(root->right, res);
}
}
vector<int> inOrder(TreeNode* root){
vector<int> res;
if(root != NULL){
stack<PR> stk;
stk.push({root, 0});
res.push_back(root->val);
while(!stk.empty()){
PR pr = stk.top();
stk.pop();
TreeNode* node = pr.first;
int state = pr.second;
if(state == 0){
// process left subtree
if(node->left == NULL){
stk.push({node, 1});
}else{
stk.push(pr);
res.push_back(node->left->val);
stk.push({node->left, 0});
}
}else if(state == 1){
// process right subtree
if(node->right == NULL){
stk.push({node, 2});
}else{
stk.push(pr);
res.push_back(node->right->val);
stk.push({node->right, 0});
}
}else{
if(!stk.empty()){
PR pr = stk.top();
stk.pop();
pr.second++;
stk.push(pr);
}
}
}
}
return res;
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
// method 1:
// inOrder(root, res);
// method 2:
res = inOrder(root);
return res;
}
};

浙公网安备 33010602011771号