题目:
Given a binary tree, return the preorder traversal of its nodes' values.
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
解答:
这题难在使用迭代而不是递归。思考一下,先序遍历过程中是不是处理根之后,根的左子树变成新的根,还有子树继续变成根……是不是很像一种数据结构:栈。
思路是这样:
- vector 存入当前根(先序处理根);
- 处理根之后再去处理左子树,左子树成为下一轮的根。那右子树怎么办?存入栈中;
- 左子树都处理完了,出栈最近的右子树成为新根。
/**
* Definition for binary tree
* 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) {
vector<int> result;
result.clear();
if(root == NULL) return result;
stack<TreeNode*> right;
TreeNode* tmp = root;
bool tag = true;
while(tag || !right.empty())
{
tag = false;
while(tmp != NULL)
{
if(tmp->right != NULL)
{
right.push(tmp->right);
}
result.push_back(tmp->val);
tmp = tmp->left;
}
if(!right.empty())
{
tag = true;
tmp = right.top();
right.pop();
}
}
return result;
}
};
代码有几个注意点:
- 处理空树;
- tag 的使用:防止最开始栈为空的情况、防止栈中取最后一个右子树之后但还未处理的情况。
后来找到最高票答案,某改……
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> nodeStack;
vector<int> result;
//base case
if(root==NULL)
return result;
nodeStack.push(root);
while(!nodeStack.empty())
{
TreeNode* node= nodeStack.top();
result.push_back(node->val);
nodeStack.pop();
if(node->right)
nodeStack.push(node->right);
if(node->left)
nodeStack.push(node->left);
}
return result;
}
};