题目:
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?
来源:http://oj.leetcode.com/problems/binary-tree-inorder-traversal/
思路:
常规的递归调用Inorder Traversal。中序遍历顺序是left->root->right
C++ AC代码:
/**
* 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> result;
vector<int> inorderTraversal(TreeNode *root) {
Inorder(root);
return result;
}
void Inorder(TreeNode *root){
if(root!=NULL){
Inorder(root->left);
result.push_back(root->val);
Inorder(root->right);
}
}
};
运行时间:8ms