Given a binary tree, return the inorder traversal of its nodes' values.
Have you met this question in a real interview? Yes ExampleGiven binary tree {1,#,2,3},
1 \ 2 / 3
return [1,3,2].
解题思路:
递归。与前序遍历代码几乎相同,仅仅是调整了顺序。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: A Tree * @return: Inorder in ArrayList which contains node values. */ vector<int> result; vector<int> inorderTraversal(TreeNode * root) { // write your code here if(root == NULL) return result; if(root->left != NULL) result = inorderTraversal(root->left); result.push_back(root->val); if(root->right != NULL) result = inorderTraversal(root->right); return result; } };