Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
三个题目类似,我就放在一起,分别是树的先序遍历,中序遍历和后序遍历。递归解法是非常简单的,也可以AC。
但是题目中有一句话Note: Recursive solution is trivial, could you do it iteratively? 最近递归用多了,迭代都不会用了,有时间再想想迭代的方法。
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> v;
travel(root,v);
return v;
}
private:
void travel(TreeNode* root,vector<int> &v){
if(root == NULL){
return ;
}
//先序遍历
//v.push_back(root->val);
travel(root->left,v);
//中序遍历
v.push_back(root->val);
travel(root->right,v);
//后序遍历
//v.push_back(root->val);
}
};