当前位置: 首页 > news >正文

【二叉树学习7】

力扣236.二叉树的最近公共祖先

链接: link

思路

要找p,q的公共祖先,可以从下往上遍历二叉树,而二叉树的后序遍历是天然的从下往上遍历。这题采用的是递归的方法,递归结束条件就是root为null或者root=p或者root=q就结束递归。
然后说一下单层逻辑,当左右子树都不为空的时候,说明分别在左右子树找到了p和q,这个时候当前节点root就是最近的公共祖先;当左子树空、右子树不为空,则说明p,q出现在右子树,此时右子树的节点是最近的公共祖先;当左子树不为空、右子树为空同理;当左右子树都为空时,则说明二叉树中没有pq。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q)
            return root;// 遍历过程遇到p,q就结束递归
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        } else if (left == null && right != null) {
            return right;
        } else if (left != null && right == null) {
            return left;
        } else {
            return null;
        }
    }
}

235.二叉搜索树的最近公共祖先
链接: link

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null)
            return root;
        if (root.val > p.val && root.val > q.val) { // pq在root左侧
            return lowestCommonAncestor(root.left, p, q);
        } else if (root.val < p.val && root.val < q.val) {// pq在root右侧
            return lowestCommonAncestor(root.right, p, q);
        }else{
            return root;
        }
    }
}

701.二叉搜索树中的插入操作
链接: link

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        List<Integer> res = new ArrayList<>();
        inorder(root, res);
        
        // 直接将元素插入到已排序的数组中
        insertIntoSortedList(res, val);
        
        // 使用修改后的数组构建新树
        return buildTree(res, 0, res.size() - 1);
    }
    
    // 中序遍历
    void inorder(TreeNode root, List<Integer> res) {
        if (root == null) return;
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }
    
    // 在递增数组中插入元素
    void insertIntoSortedList(List<Integer> res, int val) {
        int left = 0, right = res.size() - 1;
        
        // 使用二分查找插入新元素
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (res.get(mid) == val) {
                return;  // 如果值已存在,则不插入
            } else if (res.get(mid) < val) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        // 在left位置插入新的元素
        res.add(left, val);
    }

    // 构建树
    private TreeNode buildTree(List<Integer> res, int left, int right) {
        if (left > right) {
            return null;
        }
        
        int mid = left + (right - left) / 2;  // 选择中间元素作为根节点
        TreeNode root = new TreeNode(res.get(mid));
        
        root.left = buildTree(res, left, mid - 1);  // 左子树
        root.right = buildTree(res, mid + 1, right); // 右子树
        
        return root;
    }
}

递归方法

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) // 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。
            return new TreeNode(val);
            
        if (root.val < val){
            root.right = insertIntoBST(root.right, val); // 递归创建右子树
        }else if (root.val > val){
            root.left = insertIntoBST(root.left, val); // 递归创建左子树
        }
        return root;
    }
}

相关文章:

  • 【NLP 21、实践 ③ 全切分函数切分句子】
  • webpack打包优化策略
  • SpringMVC环境搭建
  • 数据库——韩顺平(每日进行更新,直至更完)
  • 【Git】三、远程管理
  • Java 大视界 -- 深度洞察 Java 大数据安全多方计算的前沿趋势与应用革新(52)
  • MySQL数据库误删恢复_mysql 数据 误删
  • 物联网领域的MQTT协议,优势和应用场景
  • 大模型参数规模解析:32B中的“B“代表什么?如何影响AI性能?
  • C# CultureInfo 地区影响字符串
  • 如何通过腾讯 ima.copilot 训练自己的知识库
  • Repo、manifest以及Gerrit分别是什么?
  • C#的async异步方法里如果使用了await,那么它跟同步方法有什么区别?
  • KubeSphere 和 K8s 高可用集群离线部署全攻略
  • 解决No matching client found for package name xxx编译报错的问题
  • 软考高级《系统架构设计师》知识点(二)
  • Vue.js 与低代码开发:如何实现快速应用构建
  • git 克隆指定 tag 的项目
  • 基于MATLAB的沥青试样孔隙率自动分析——原理详解与代码实现
  • (前端基础)HTML(一)
  • 王毅:时代不容倒退,公道自在人心
  • 【社论】人工智能,年轻的事业
  • 国家核准10台核电新机组,四大核电央企披露新项目进展
  • 幸福航空五一前三天航班取消:客服称目前是锁舱状态,无法确认何时恢复
  • 牛市早报|今年国内核电项目审批首次开闸,离境退税起退点下调
  • 滨江集团去年营收约691亿元,尚未结算的预收房款1253亿元