【LeetCode】94. 二叉树的中序遍历

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuqiuai/article/details/83381917

题目链接https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/

题目描述

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

示例

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

2
/
3

输出: [1,3,2]

解决方法

采用递归,深度优先遍历

/**
 * 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 {
    vector<int> res;
public:
    vector<int> inorderTraversal(TreeNode* root) {
        //采用递归,深度优先遍历
        if (root){
            inorderTraversal(root->left);
            res.push_back(root->val);
            inorderTraversal(root->right);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/fuqiuai/article/details/83381917