二叉树的前序遍历
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,2,3].
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
void pretrav(TreeNode *root,vector<int> &r){
if(root==NULL) return;
r.push_back(root->val);
pretrav(root->left,r);
pretrav(root->right,r);
}
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
pretrav(root,v);
return v;
}
};
二叉树的中序遍历
给出一棵二叉树,返回其中序遍历
给出二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,3,2].
void intrav(TreeNode *root,vector<int> &r){
if(root==NULL) return;
intrav(root->left,r);
r.push_back(root->val);
intrav(root->right,r);
}
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
intrav(root,v);
return v;
}
二叉树的后序遍历
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [3,2,1]
void posttrav(TreeNode *root,vector<int> &r){
if(root==NULL) return;
posttrav(root->left,r);
posttrav(root->right,r);
r.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
posttrav(root,v);
return v;
}