Description
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree[1,null,2,3]
,
1
\
2
/
3
return
[1,3,2]
.
Solution
思路:题意为中序遍历二叉树。遍历顺序为左—>根—>右,考虑到用递归比较简单,本文使用递归的思想进行解决。
/**
* Definition for binary tree
* struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:
void inOrderTraversal(vector<int>& vi,TreeNode* root)
{
if(root->left) inOrderTraversal(vi,root->left);
vi.push_back(root->val);
if(root->right) inOrderTraversal(vi,root->right);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> vi;
if(!root) return vi;
inOrderTraversal(vi,root);
return vi;
}
};