二叉树最小深度&根据遍历结果构建二叉树

本文介绍了一种求解二叉树最小深度的方法,并通过中序和后序遍历结果构建二叉树。提供了完整的C++代码实现,包括递归求解最小深度和根据遍历结果构建树的具体步骤。

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

leetcode_01

minimum-depth-of-binary-tree

求二叉树的最小深度

class Solution
{
public:
    int run(TreeNode *root)
    {
        if(root == NULL)
        {
            return 0;
        }
        if(root->left == NULL && root->right == NULL)
        {
            return 1;
        }
        if(root->left == NULL)
        {
            return run(root->right) + 1;
        }
        if(root->right == NULL)
        {
            return run(root->left) + 1;
        }
        if(root->left != NULL && root->right != NULL)
        {
            int leftDepth = run(root->left) + 1;
            int rightDepth = run(root->right) + 1;
            return (leftDepth > rightDepth) ? rightDepth : leftDepth;
        }
        return 0;
    }
};

根据中序遍历和后序遍历结果构建二叉树

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution
{
public:

    //在中序遍历序列中找到根结点的位置
    int findRoot(vector<int> &array, int start, int end, int key)
    {
        for (int i = start; i <= end; i++)
        {
            if (array[i] == key)
            {
                return i;
            }
        }
        return -1;
    }

    TreeNode *build(vector<int> &inorder, int inStart, int inEnd, 
                    vector<int> &postorder, int postStart, int postEnd)
    {
        if (inStart > inEnd)
        {
            return NULL;
        }

        //根据后序遍历序列的最后一个数字建立根结点root
        TreeNode *root = new TreeNode(postorder[postEnd]);

        //获取根结点的位置position
        int position = findRoot(inorder, inStart, inEnd, postorder[postEnd]);
        //创建左子树
        root->left = build(inorder, inStart, position - 1, 
                           postorder, postStart, 
                           postStart + (position - inStart - 1));
        //创建右子树
        root->right = build(inorder, position + 1, inEnd, 
                            postorder, postStart + (position - inStart), 
                            postEnd - 1);

        return root;    //返回根结点
    }

    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        if(inorder.size() != postorder.size())
            return NULL;
        return build(inorder, 0, inorder.size() - 1, 
                     postorder, 0, postorder.size() - 1);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值