二叉树的中序遍历-LintCode

本文介绍了一种计算二叉树中序遍历序列的方法,提供了递归及非递归两种算法实现,并详细解释了非递归算法的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出一棵二叉树,返回其中序遍历

样例
给出二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [1,3,2].

挑战
你能使用非递归算法来实现么?

#ifndef C66_H
#define C66_H
#include<vector>
#include<iostream>
#include<stack>
using namespace std;
class TreeNode {
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val) {
        this->val = val;
        this->left = this->right = NULL;
    }
};
//递归
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        //TreeNode *node = root;
        vector<TreeNode*> tVal;
        vector<int> res;
        while (root != NULL || tVal.size() != 0)
        {


                while (root != NULL){
                    tVal.push_back(root);
                    root = root->left;
                }
                root = tVal.back();
                tVal.pop_back();
                res.push_back(root->val);
                root = root->right;

        }
        return res;
    }
};
//非递归
class Solution2 {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> res;
        stack<TreeNode*> stack;
        TreeNode *node = root;
        //访问结点node,并将结点入栈
        //若其左孩子为空,取栈顶元素并出栈,将栈顶元素的右孩子作为当前结点
        //若其左孩子不为空,将其左孩子作为当前结点
        //直至node==NULL且栈为空
        while (node || !stack.empty())
        {
            while (node)
            {
                stack.push(node);
                node = node->left;
            }
            if (!stack.empty())
            {
                node = stack.top();
                stack.pop();
                res.push_back(node->val);
                node = node->right;
            }
        }
        return res;
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值