题目描述:

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].

Note: Recursive solution is trivial, could you do it iteratively?

解题思路:

利用递归一路从左往下,然后添加当前节点,最后再从右往下,遇到节点为空则返回。

代码:

 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     void inorder(vector<int> &nums, TreeNode* root){
13         if(root){
14             inorder(nums, root->left);  //一路左
15             nums.push_back(root->val);  //添加当前节点
16             inorder(nums, root->right);  //最后往右
17         }
18     }
19     vector<int> inorderTraversal(TreeNode* root) {
20         vector<int> nums;
21         inorder(nums, root);
22         return nums;
23     }
24 };

 

 

 

posted on 2018-03-23 22:23  宵夜在哪  阅读(80)  评论(0编辑  收藏  举报