LeetCode94——Binary Tree Inorder Traversal
LeetCode94——Binary Tree Inorder Traversal
出去调了一天代码,回来就调了两道简单的题目写了。。。
先来一道二叉树的中序遍历,直接递归解决就ok。
原题
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].
代码
LeetCode里面数据结构的题链表的题目已经做了不少,现在开始轮到二叉树了,要慢慢拾起来了。
class Solution {
private:
void helper(TreeNode*root, vector<int>&result)
{
if (root == NULL)
return;
helper(root->left,result);//递归左子树
result.push_back(root->val);//访问根
helper(root->right,result);//递归右子树
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>result;
helper(root, result);
return result;
}
};
还没有评论,来说两句吧...