本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Binary Tree Inorder Traversal
Total Accepted: 16984 Total
Submissions: 48800
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.
题意:中序遍历
思路:采用递归实现。因为函数声明是返回一个vector<int>,所以每个子树返回的是该子树的中序遍历的结果
按照 左、根、右的次序把根和左右子树的vector合并起来就可以了
复杂度:时间O(n),空间O(n)
相关题目:
Binary Tree Preorder Traversal
/** * Definition for binary tree * 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> in; if(root == NULL) return in; TreeNode *left = root->left; TreeNode *right = root->right; if(left) { vector<int> left_vector = inorderTraversal(left); in.insert(in.end(), left_vector.begin(), left_vector.end()); } in.push_back(root->val); if(right){ vector<int> right_vector = inorderTraversal(right); in.insert(in.end(), right_vector.begin(), right_vector.end()); } return in; } };
Leetcode 树 Binary Tree Inorder Traversal
时间: 2024-12-29 19:01:33