首页 > 编程语言 >代码随想录算法 - 二叉树3

代码随想录算法 - 二叉树3

时间:2024-09-13 18:36:03浏览次数:1  
标签:right int inorder 随想录 iter 算法 二叉树 root 节点

题目1513. 找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

示例 1:

img

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

示例 2:

img

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7

提示:

  • 二叉树的节点个数的范围是 [1,104]
  • -231 <= Node.val <= 231 - 1

思路

迭代法

用辅助queue进行层序遍历就行了,直到最后一层遍历完,取出最左边的节点。

代码

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        if(!root->left && !root->right)
        {
            return root->val;
        }
        queue<TreeNode*> nodeQueue;
        TreeNode* result;
        nodeQueue.push(root);
        while(!nodeQueue.empty())
        {
            int num = nodeQueue.size();
            if(num > 0)
            {
                result = nodeQueue.front();
            }
            for(int i = 0; i < num; i++)
            {
                TreeNode* curNode = nodeQueue.front();
                nodeQueue.pop();
                if(curNode->left)
                {
                    nodeQueue.push(curNode->left);
                }
                if(curNode->right)
                {
                    nodeQueue.push(curNode->right);
                }
            }
        }
        return result->val;
    }
};

递归法

用辅助变量maxdepth和depth来判断叶子节点是否是左下角的节点,其他的部分就先序遍历做就行了。

代码

class Solution {
public:
    int result;
    int maxDepth;
    void getResult(TreeNode* root, int depth)
    {
        //碰到叶子节点判断是否为最深的左叶子
        if(!root->left && !root->right)
        {
            if(depth > maxDepth)
            {
                maxDepth = depth;
                result = root->val;
            }
            return;
        }
        if(root->left)
        {
            getResult(root->left, depth + 1);
        }
        if(root->right)
            getResult(root->right, depth + 1);
    }
    int findBottomLeftValue(TreeNode* root) {
        maxDepth = INT_MIN;
        getResult(root, 0);
        return result;
    }
};

题目2 112. 路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false

叶子节点 是指没有子节点的节点。

示例 1:

img

输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。

示例 2:

img

输入:root = [1,2,3], targetSum = 5
输出:false
解释:树中存在两条根节点到叶子节点的路径:
(1 --> 2): 和为 3
(1 --> 3): 和为 4
不存在 sum = 5 的根节点到叶子节点的路径。

示例 3:

输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。

提示:

  • 树中节点的数目在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

思路

递归法

用先序遍历,注意节点是否为叶子节点就行了。

代码

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr)
        {
            return false;
        }
        int curVal = targetSum - root->val;
        if(curVal == 0 && !root->left && !root->right)
        {
            return true;
        }
        return hasPathSum(root->left, curVal) || hasPathSum(root->right, curVal);     
    }
};

迭代法

我使用一个辅助栈stack<pair<TreeNode*, int>>对象来保存每个节点及剩余的路径,剩下的用什么遍历都可以找出目标叶子节点。

代码

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr)
        {
            return false;
        }
        stack<pair<TreeNode*, int>> nodeStack;
        nodeStack.push(make_pair(root, targetSum));
        while(!nodeStack.empty())
        {
            auto iter = nodeStack.top();
            nodeStack.pop();
            if(!iter.first->left && !iter.first->right && iter.first->val == iter.second)
            {
                return true;
            }
            if(iter.first->left)
            {
                nodeStack.push(make_pair(iter.first->left, iter.second - iter.first->val));
            }
            if(iter.first->right)
            {
                nodeStack.push(make_pair(iter.first->right, iter.second - iter.first->val));
            }
        }
        return false;
    }
};

题目3 106. 从中序与后序遍历序列构造二叉树

给定两个整数数组 inorderpostorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树

示例 1:

img

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

迭代法

用的迭代法,思路和代码随想里的递归法类似。

代码

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.empty() || postorder.empty()) return nullptr;

        // 根节点
        TreeNode* root = new TreeNode(postorder.back());
        postorder.pop_back(); // 删除最后一个元素,因为这是根节点
        
        // 找到根节点在 inorder 中的索引
        int rootIndex = 0;
        while (inorder[rootIndex] != root->val) {
            rootIndex++;
        }

        // 栈保存:parent节点,inorder左边界,inorder右边界,postorder左边界,postorder右边界,是否为左子树
        stack<tuple<TreeNode*, int, int, int, int, bool>> nodeStack;

        // 处理右子树
        if (rootIndex + 1 <= inorder.size() - 1) {
            nodeStack.push(make_tuple(root, rootIndex + 1, inorder.size() - 1, rootIndex, postorder.size() - 1, false));
        }

        // 处理左子树
        if (0 <= rootIndex - 1) {
            nodeStack.push(make_tuple(root, 0, rootIndex - 1, 0, rootIndex - 1, true));
        }

        // 遍历栈
        while (!nodeStack.empty()) {
            auto [parent, inStart, inEnd, postStart, postEnd, isLeft] = nodeStack.top();
            nodeStack.pop();

            // 新的根节点是后序遍历 postorder[postEnd] 的值
            TreeNode* curNode = new TreeNode(postorder[postEnd]);

            if (isLeft) {
                parent->left = curNode;
            } else {
                parent->right = curNode;
            }

            // 在 inorder 中找到当前节点的索引
            int inIndex = inStart;
            while (inorder[inIndex] != curNode->val) {
                inIndex++;
            }

            // 处理右子树
            if (inIndex + 1 <= inEnd) {
                nodeStack.push(make_tuple(curNode, inIndex + 1, inEnd, postEnd - (inEnd - inIndex), postEnd - 1, false));
            }

            // 处理左子树
            if (inStart <= inIndex - 1) {
                nodeStack.push(make_tuple(curNode, inStart, inIndex - 1, postStart, postStart + (inIndex - inStart) - 1, true));
            }
        }

        return root;
    }
};

标签:right,int,inorder,随想录,iter,算法,二叉树,root,节点
From: https://www.cnblogs.com/code4log/p/18412691

相关文章

  • leetcode刷题day17|二叉树Part05(654.最大二叉树、617.合并二叉树、700.二叉搜索树中的
    654.最大二叉树构造树一般采用的是前序遍历,因为先构造中间节点,然后递归构造左子树和右子树。递归三步曲:1、传入参数,整数数组,数组的开始和结束,返回树的中间节点。2、终止条件:开始大于等于结束,即数组为空。3、递归逻辑:找到最大的元素,记录元素其下标,构建中间节点;递归构造......
  • 文心一言 VS 讯飞星火 VS chatgpt (346)-- 算法导论23.2 5题
    五、假定图中边的权重取值全部为整数,且在范围内。Prim算法最快能多快?如果边的权重取值范围在1到某个常数之间呢?如果要写代码,请用go语言。文心一言:Prim算法是一种用于寻找加权无向图的最小生成树的贪心算法。其时间复杂度主要取决于实现方式。在标准实现中,Prim算法通常使用优先队列(......
  • 行驶证识别算法以及在中科麒麟系统的离线部署
    行驶证作为车辆合法上路的证明文件,包含车辆的基本信息和车主的详细资料,是政府部门、保险公司、租赁公司以及交通管理系统中常用的文档。在日常业务操作中,快速、准确地录入行驶证信息对于提高工作效率、减少人工错误有着重要意义。然而,传统的手工输入过程不仅费时,还存在一定的错误......
  • 【数据结构】第八节:链式二叉树
    个人主页: NiKo数据结构专栏: 数据结构与算法 源码获取:Gitee——数据结构一、二叉树的链式结构typedefintBTDataType;typedefstructBinaryTreeNode{ BTDataTypedata; structBinaryTreeNode*left;//左子树根节点 structBinaryTreeNode*right;//右子......
  • LRU算法原理及其实现
    一、LRU是什么        LRU算法的全称是“LeastRecentlyUsed”,即“最近最少使用”算法。LRU算法的基本思想是,当缓存空间已满时,优先淘汰最近最少使用的缓存数据,以腾出更多的缓存空间。因此,LRU算法需要维护一个缓存访问历史记录,以便确定哪些缓存数据是最近最少使用的。......
  • LeetCode算法—分治法
    思路:分治法的核心思想是“分而治之”,即将一个复杂的问题分成多个较小的子问题,分别求解这些子问题,然后将子问题的解合并,得到原问题的解。具体到求众数的问题上,分治法通过递归地将数组分成两部分,分别找出每一部分的众数,最后通过合并步骤来确定整个数组的众数。LeetCode169多数元素......
  • 代码随想录突击版刷题
    704.二分查找https://leetcode.cn/problems/binary-search/description/ 59.螺旋矩阵II https://leetcode.cn/problems/spiral-matrix-ii/description/、参考题解写出54.螺旋矩阵 https://leetcode.cn/problems/spiral-matrix/description/classSolution{public:......
  • 基于MATLAB蚁群算法优化的小波变换图像压缩
    随着计算机技术和网络速度的飞速发展,数字图像越来越成为人们生活中不可或缺的一部分,然而由于存储和传输的限制,如何对数字图像进行高效压缩成为了研究的热点问题,小波变换作为一种基于多尺度分析的信号处理方法,在数字图像压缩中有着广泛的应用。然而传统的小波变换图像压缩方法......
  • 决策树算法上篇
    决策树概述决策树是属于有监督机器学习的一种,起源非常早,符合直觉并且非常直观,模仿人类做决策的过程,早期人工智能模型中有很多应用,现在更多的是使用基于决策树的一些集成学习的算法。示例一:上表根据历史数据,记录已有的用户是否可以偿还债务,以及相关的信息。通过该数据,构建......
  • Python与Go语言中的哈希算法实现及对比分析
    哈希算法是一种将任意大小的数据输入转化为固定大小的输出(通常为一个散列值)的算法,在密码学、数据完整性验证以及数据索引等场景中广泛应用。本文将详细介绍Python和Go语言如何实现常见的哈希算法,包括MD5、SHA-1、SHA-256等。文章不仅提供代码示例,还会详细解释每个算法的特点、应用......