欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 94. 二叉树的中序遍历 C++

程序员文章站 2022-05-20 13:49:37
...

Leetcode 94. 二叉树的中序遍历

题目

给定一个二叉树,返回它的中序 遍历。

测试样例

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

题解

递归实现中序遍历

代码

vector<int> ans;
    void search(TreeNode* root){
        if(root->left){
            search(root->left);
        }
        ans.push_back(root->val);
        if(root->right){
            search(root->right);
        }
    }
    vector<int> inorderTraversal(TreeNode* root) {
        if(root == NULL)    return ans;
        search(root);
        return ans;
    }

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。