Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},1
\
2
/
3return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
思路
先序遍历,递归和非递归
递归的时候要重写一个函数,因为要把vector< int>代入
非递归就是栈了
代码–递归
/**
* 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 preorder(TreeNode* t, vector<int> &v)
{
if(t!=NULL)
{
v.push_back(t->val);
preorder(t->left,v);
preorder(t->right,v);
}
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root,res);
return res;
}
};
代码–非递归
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL)
return res;
stack<TreeNode *> TS;
TS.push(root); //根节点进栈
while(!TS.empty())
{
TreeNode * cur = TS.top();//根节点取元素
TS.pop();//出栈
res.push_back(cur->val);
if(cur->right!=NULL)//右
TS.push(cur->right);
if(cur->left!=NULL)//左
TS.push(cur->left);
}
return res;
}
};