94. 二叉树的中序遍历

题目描述

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

示例1.

输入:root = [1,null,2,3]
输出:[1,3,2]

示例2.

输入:root = []
输出:[]

示例3.

输入:root = [1]
输出:[1]

题目链接

解题思路: 

方法1. 递归

题目要求的是中序遍历,那就按照 左-打印-右这种顺序遍历树就可以

终止条件:当前节点为空时
函数内:递归的调用左节点,打印当前节点,再递归调用右节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>newRes;  
        traverse(root, newRes);
        return newRes;
    }
    void traverse(TreeNode* root, vector<int>& res){
        if(root==nullptr){
            return;
        }
        traverse(root->left, res);
        res.push_back(root->val);
        traverse(root->right, res);
    }
};

方法2. 迭代

 递归的调用过程是不断往左边走,当左边走不下去了,就打印节点,并转向右边,然后右边继续这个过程。我们在迭代实现时,就可以用栈来模拟上面的调用过程。

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*>calc;
        vector<int>res;
        while(!calc.empty() || root!=nullptr){
            if(root!=nullptr){
                calc.push(root);
                root=root->left;
            }
            else{
                TreeNode* cur = calc.top();
                res.push_back(calc.top()->val);
                calc.pop();
                root=cur->right; 
            }
        }
        return res;   
    }   
};

 

 迭代步骤如上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值