题目:
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.
思路:
经典的中序排序算法,可以用递归实现,也可以用带权重的堆栈实现。
代码:
/**
* 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) {
if(root == NULL){
return vector<int>();
}
vector<int> left = inorderTraversal(root->left);
left.push_back(root->val);
vector<int> right = inorderTraversal(root->right);
for(int i = 0; i < right.size(); i++){
left.push_back(right[i]);
}
return left;
}
};