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 };
View Code

 

posted @ 2018-08-27 19:34  gszzsg  阅读(113)  评论(0编辑  收藏  举报