Leetcode解题报告:94. Binary Tree Inorder Traversal
2016-10-04 00:52
381 查看
题意:Given a binary tree, return the inorder traversal
of its nodes' values.
难度:Medium
解题思路:简单的中序遍历问题,当根节点存在左子树的时候,先遍历左子树,当返回到跟结点的时候,把根节点值加入答案数组,再遍历右子树(如果存在的话)。时间复杂度O(n),如果当前结点没有左右子树,当前值也要加入答案数组。
/**
* 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 helper(vector<int> & ans,TreeNode* root)
{
if(root==NULL)
return;
if(root->left!=NULL)
{
helper(ans,root->left);
}
ans.push_back(root->val);
if(root->right!=NULL)
{
helper(ans,root->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
helper(ans,root);
return ans;
}
};
of its nodes' values.
难度:Medium
解题思路:简单的中序遍历问题,当根节点存在左子树的时候,先遍历左子树,当返回到跟结点的时候,把根节点值加入答案数组,再遍历右子树(如果存在的话)。时间复杂度O(n),如果当前结点没有左右子树,当前值也要加入答案数组。
/**
* 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 helper(vector<int> & ans,TreeNode* root)
{
if(root==NULL)
return;
if(root->left!=NULL)
{
helper(ans,root->left);
}
ans.push_back(root->val);
if(root->right!=NULL)
{
helper(ans,root->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
helper(ans,root);
return ans;
}
};
相关文章推荐
- Climbing Stairs | leetcode 70 【Java解题报告】
- [LeetCode] Search for a Range 解题报告
- 【LeetCode】496. Next Greater Element I 解题报告
- [LeetCode] Triangle 解题报告
- leetcode(16) 3Sum Closest解题报告
- [Leetcode] 75. Sort Colors 解题报告
- [Leetcode] 304. Range Sum Query 2D - Immutable 解题报告
- [Leetcode] 78. Subsets 解题报告
- LeetCode: Subsets 解题报告
- [Leetcode] 396. Rotate Function 解题报告
- [Leetcode] 398. Random Pick Index 解题报告
- 【LeetCode】290.Word Pattern解题报告
- [leetcode] 246. Strobogrammatic Number 解题报告
- LeetCode 64. Minimum Path Sum 解题报告
- [leetcode] 288. Unique Word Abbreviation 解题报告
- [leetcode] 287. Find the Duplicate Number 解题报告
- [Leetcode] 634. Find the Derangement of An Array 解题报告
- Leetcode 468. Validate IP Address 验证IP地址 解题报告
- [Leetcode] 307. Range Sum Query - Mutable 解题报告
- [Leetcode] 408. Valid Word Abbreviation 解题报告