94. Binary Tree Inorder Traversal
题目描述:
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
解题思路:
递归的方法。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 vector<int> ret; 14 ret.reserve(1000); 15 traversal(root, ret); 16 return ret; 17 } 18 void traversal(TreeNode* root, vector<int>& ret) { 19 if (root == NULL) 20 return; 21 traversal(root->left, ret); 22 ret.push_back(root->val); 23 traversal(root->right, ret); 24 } 25 };