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]
.
题目的意思是中序遍历二叉树,保存并返回按中序遍历的结点的值。
中序遍历顺序为左,中,右。显然采用递归的方法比较简单。
设置一个inOrder函数,完成递归。
/**
* 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 {
public:
vector<int> list;
void inOrder(TreeNode *node)
{
if (node == NULL)
return;
if (node->left != NULL)
inOrder(node->left);
list.push_back(node->val);
if (node->right != NULL)
inOrder(node->right);
}
vector<int> inorderTraversal(TreeNode* root)
{
inOrder(root);
return list;
}
};