Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
题目大意:写出二叉树的非递归前序遍历的方法。
解题思路:和中序遍历的那一道题类似,处理过程如下:
对于任意节点N:
1. 访问N并将N入栈
2. 判断结点N的左孩子是否为空,若为空,则取栈顶结点并进行出栈操作,并将栈顶结点的右孩子置为当前结点N,循环至1;若不为空,则将N的左孩子置为当前结点N
3. 直到N为空且栈也为空,遍历结束
参考资料:http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
代码如下:
/**
* 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) {
if(root == nullptr) return vector<int>();
stack<TreeNode*> stk;
vector<int> ans;
TreeNode* now = root;
while(now || stk.size()){
while(now){
stk.push(now);
ans.push_back(now->val);
now = now->left;
}
if(stk.size()){
now = stk.top();
stk.pop();
now = now->right;
}
}
return ans;
}
};