LeetCode OJ入门初探-94. 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].

Note: Recursive solution is trivial, could you do it iteratively?

confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

Subscribe to see which companies asked this question

讲道理题目不难,就是对树的中序遍历,常用的就是递归方式,在左子树不为空时,递归左子树,再把root放入便利,在右子树不为空时,把右子树放入递归。这种方法很通用,对于前序,后序都可以。但是效率不高,对于使用循环可以提高效率,思路也是如此。


/**
* 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 {
//vector num;
public:
vector inorderTraversal(TreeNode* root) {
vector num;
if(root==NULL)
return num;
if(root->left!=NULL)
{
vector temp = inorderTraversal(root->left);
num.insert(num.end(), temp.begin(), temp.end());
//copy(temp.begin(),temp.end(),)
}
num.push_back(root->val);
if(root->right!=NULL)
{
vector temp = inorderTraversal(root->right);
num.insert(num.end(), temp.begin(), temp.end());
//copy(temp.begin(),temp.end(),)
}
return num;
}
};

发表评论