【简单】Lintcode 67:Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

Example

Given 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;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80293020
今日推荐