题意:给你一颗二叉树,返回先序遍历的节点vector。
解题思路:
思路一:递归,比较容易想到,递归终止条件是当前指针为空,递归规则是先把当前节点放进vector,然后递归当前节点的左子树,然后递归右子树。
思路二:使用栈,栈的特性是先进后出,规则是:先把栈顶元素放进vector,然后把该元素的右子树节点放进去,然后把左子树节点放进去。取的时候会先取出左子树,然后再取右子树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//use stack to solve this problem is available.
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> istack;
istack.push(root);
while(!istack.empty()){
TreeNode* fr = istack.top();
istack.pop();
if(!fr)
continue;
ans.push_back(fr->val);
istack.push(fr->right);
istack.push(fr->left);
}
return ans;
}
};