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

【二叉树学习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;
    }
}

http://www.kler.cn/a/546944.html

相关文章:

  • Eclipse:关闭多余的工具条
  • Docker compose 以及镜像使用
  • Sprinig源码解析
  • [LeetCode]day21 15.三数之和
  • Machine Learning:Optimization
  • H5自适应响应式代理记账与财政咨询服务类PbootCMS网站模板 – HTML5财务会计类网站源码下载
  • HCIA项目实践---OSPF的基本配置
  • 在本地校验密码或弱口令 (windows)
  • DeepSeek免费部署到WPS或Office
  • Linux 内核 IPoIB 驱动中 sysfs 属性冲突问题的分析与解决
  • LAWS是典型的人机环境系统
  • 【第4章:循环神经网络(RNN)与长短时记忆网络(LSTM)— 4.6 RNN与LSTM的变体与发展趋势】
  • Unity使用iTextSharp导出PDF-04图形
  • 修改OnlyOffice编辑器默认字体
  • 小米 R3G 路由器刷机教程(Pandavan)
  • 算法练习——哈希表
  • QML使用ChartView绘制箱线图
  • harmonyOS的文件的增、删、读、写相关操作(fs/content)
  • 土星云边缘计算微服务器 SE110S-WA32加持DeepSeek,本地部署企业私有推理大模型!
  • 父组件中循环子组件调用