lintcode——二叉树的中序遍历
2017-04-08 00:30
309 查看
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 {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
std::vector<int> t;
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
if(root==NULL) return t;
else{
inorderTraversal(root->left);
t.push_back(root->val);
inorderTraversal(root->right);
}
return t;
}
};
4、感想
写了前序遍历之后对递归有了点眉目,写起中序遍历来就很快了。两个题的代码也几乎一样。
给出一棵二叉树,返回其中序遍历
样例
给出二叉树
{1,#,2,3},
1 \ 2 / 3
返回
[1,3,2].
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 {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
std::vector<int> t;
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
if(root==NULL) return t;
else{
inorderTraversal(root->left);
t.push_back(root->val);
inorderTraversal(root->right);
}
return t;
}
};
4、感想
写了前序遍历之后对递归有了点眉目,写起中序遍历来就很快了。两个题的代码也几乎一样。
相关文章推荐
- LintCode Binary Tree Inorder Traversal 二叉树的中序遍历(非递归)
- lintcode 容易题:Binary Tree Inorder Traversal 二叉树的中序遍历
- LintCode -- 二叉树的中序遍历
- LintCode:二叉树的前序遍历、中序遍历、后序遍历
- 二叉树中路径和为某整数的所有路径 lint code by python
- LintCode:二叉树的层次遍历 II
- LintCode 二叉树的所有路径
- 算法题:lintcode#175 翻转二叉树(java)
- lintcode--二叉树中的最大路径和
- lintcode,二叉树的后序遍历
- lintcode——翻转二叉树
- lintcode--二叉树的锯齿形层次遍历
- LintCode 67 二叉树的后序遍历
- LintCode 解题记录 17.5.8 (tag:二叉树)
- lintcode 二叉树的层次遍历系列问题 -解决方法和领会
- Lintcode:二叉树的最大节点
- LintCode:二叉树的最大深度
- lintcode——二叉树的最大深度
- lintcode:将二叉树拆成链表
- LintCode2016年算法比赛----二叉树的所有路径