zoukankan      html  css  js  c++  java
  • (二叉树 递归) leetcode94. 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]

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

    ---------------------------------------------------------------------------------------------------------------

    leetcode 144. Binary Tree Preorder Traversal 几乎相似。题目要求我们尽量用迭代求解,不过,我不太会,所以用递归。

    C++代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            vector<int> vec;
            inorder(root,vec);
            return vec;
        }
        void inorder(TreeNode *root,vector<int> &vec){
            if(!root) return;
            inorder(root->left,vec);
            vec.push_back(root->val);
            inorder(root->right,vec);
        }
    };
  • 相关阅读:
    CentOS随笔
    CentOS随笔
    CentOS随笔
    CentOS随笔
    产品从生到死的N宗罪
    即将结束的2015。
    Mvvm
    android 热补丁修复框架
    反编译APK
    关于短视频
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10773734.html
Copyright © 2011-2022 走看看