首页 > 其他分享 >【DFS】LeetCode 235. 二叉搜索树的最近公共祖先

【DFS】LeetCode 235. 二叉搜索树的最近公共祖先

时间:2023-02-03 12:22:42浏览次数:61  
标签:right TreeNode subtree DFS return 235 root LeetCode left

题目链接

235. 二叉搜索树的最近公共祖先

思路

【DFS】LeetCode 236. 二叉树的最近公共祖先 一模一样

代码

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q){
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        // p and q are not in left subtree
        if(left == null){
            return right;
        }
        // p and q are not in right subtree
        if(right == null){
            return left;
        }

        // p and q are in the left subtree and right subtree respectively
        return root;
    }
}

标签:right,TreeNode,subtree,DFS,return,235,root,LeetCode,left
From: https://www.cnblogs.com/shixuanliu/p/17088736.html

相关文章

  • Sequence Decoding (DFS)
    给出一个字符串,只含【,】,H,P,和数字,要把这些数字和中括号里的字母展开复制多少遍根据中括号外面的数字决定。用深搜来做,遇到数字就记录数字多少,遇到【就进深一度的搜索,如果数H......
  • 【DFS】LeetCode 236. 二叉树的最近公共祖先
    题目链接236.二叉树的最近公共祖先思路代码classSolution{publicTreeNodelowestCommonAncestor(TreeNoderoot,TreeNodep,TreeNodeq){if(roo......
  • codeforces 580C Kefa and Park (树上DFS)
    Description:Kefadecidedtocelebratehisfirstbigsalarybygoingtotherestaurant.Helivesbyanunusualpark.Theparkisarootedtreeconsistingof n ve......
  • [LeetCode] 1145. Binary Tree Coloring Game
    Twoplayersplayaturnbasedgameonabinarytree.Wearegiventhe root ofthisbinarytree,andthenumberofnodes n inthetree. n isodd,andeach......
  • LeetCode括号生成(/)
    原题解题目数字n代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且有效的括号组合。约束解法解法一classSolution{boolvalid(conststr......
  • LeetCode 对称二叉树算法题解 All In One
    LeetCode对称二叉树算法题解AllInOne对称二叉树原理图解101.SymmetricTree对称二叉树https://leetcode.com/problems/symmetric-tree/https://leetcode.c......
  • Luogu5435 基于值域预处理的快速 GCD & Leetcode2543 - binary GCD -
    题目链接:https://www.luogu.com.cn/problem/P5435请忽略题目名称学到一个科技:binaryGCD,能够快速求出两个数GCD(从这道题来看已经接近\(O(1)\)了)代码://bySkyRainW......
  • leetcode-543二叉树直径
    //leetcodesubmitregionbegin(Prohibitmodificationanddeletion)/***Definitionforabinarytreenode.*publicclassTreeNode{*intval;*TreeNodeleft;......
  • #yyds干货盘点# LeetCode面试题:两数相加
    1.简述:给你两个 非空的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表......
  • #yyds干货盘点# LeetCode程序员面试金典:幂集
    题目:幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。说明:解集不能包含重复的子集。示例:输入:nums=[1,2,3]输出:[ [3], [1], [2], [1,2,3],......