leetcode94:二叉树的中序遍历



一、题目

网址二叉树的中序遍历

级别:中等。

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

示例:

输入: [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 {
public:
    vector<int> res; 
    vector<int> inorderTraversal(TreeNode* root) {  
        if(root==NULL) return res;
        inorderTraversal(root->left);
        res.push_back(root->val);
        inorderTraversal(root->right);

        return res;
        
    }
};

结果:
在这里插入图片描述

方法二

采用迭代的形式对二叉树进行中序遍历。

/**
 * 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) {  
        stack<TreeNode*> s;
        vector<int> res;
        while(!s.empty()||root!=NULL)
        {
            while(root!=NULL)
            {
                s.push(root);
                root=root->left;
            }
            if(!s.empty())
            {
                root=s.top();
                res.push_back(root->val);
                s.pop();
                root=root->right;
            }
        }
        return res;
    }
};

结果:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章