【leetcode】236. Lowest Common Ancestor of a Binary Tree

本文深入探讨了二叉树中寻找两个节点最低公共祖先(LCA)的算法,通过自底向上的递归方式,详细解释了如何高效地解决这一经典问题。文章提供了具体的实现代码,帮助读者理解并掌握LCA算法的核心思想。

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

 

Note:

  • All of the nodes' values will be unique.
  • p and q are different and both values will exist in the binary tree.

思考:这是一道二叉树搜索最低公共祖先结点的题,按照以往的经验,我们知道,树的问题一般可以采用递归的方式来进行编程。那么,是采用自顶向下还是自底向上呢?由于需要找最低的公共祖先结点,所以应该采用自底向上的递归方式进行编程。而且由题意我们容易知道给出的二叉树数据结点都是唯一的,所以,当我们在左子树找到p结点,而在右子树找到q结点时,我们便可以找到当前结点为p,q结点的最低公共祖先结点(因为是自底向上递归的)这里还需考虑到,如果p(q)为q(p)的祖先结点,那么p(q)就是p,q的祖先结点了。

实现代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    private TreeNode ans;
    
    public Solution(){
        this.ans = null;
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //TreeNode ans = null;
        traverse(root,p,q);
        return ans;
    }
    
    public boolean traverse(TreeNode currentNode,TreeNode p,TreeNode q){
        if(currentNode == null){
            return false;
        }
        int left = this.traverse(currentNode.left,p,q)? 1:0;
        int right = this.traverse(currentNode.right,p,q)? 1:0;
        int mid = (currentNode==p || currentNode==q)? 1:0;
        if(left + right +mid >= 2){
            ans = currentNode;
        }
        
        return (mid + left + right >0);
    }
}

 

在准备 LeetCode 面试题时,一些高频题目和经典题型是必须掌握的,这些题目覆盖了数组、字符串、链表、树、动态规划等多个方面。以下是一些常见的 LeetCode 面试题: ### 数组与双指针类问题 - **LeetCode 160. Intersection of Two Linked Lists**:判断两个链表是否相交,并找到交点。 - **LeetCode 141. Linked List Cycle**:判断链表中是否存在环。 - **LeetCode 92. Reverse Linked List II**:反转链表的指定部分。 - **LeetCode 328. Odd Even Linked List**:将链表中的奇偶节点分开并连接到一起。 - **LeetCode 面试题 16.06. 最小差**:找到两个数组中差值最小的两个数,常用双指针法解决[^4]。 ### 字符串与哈希类问题 - **LeetCode 242. Valid Anagram**:判断两个字符串是否是变位词,通常使用哈希表或数组统计字符频率来解决[^2]。 - **LeetCode 1. Two Sum**:在数组中找出两个数使其和等于目标值,常用哈希表存储差值。 - **LeetCode 49. Group Anagrams**:将变位词分组,常用于哈希表处理字符串特征。 ### 链表类问题 - **LeetCode 2. Add Two Numbers**:两个链表表示的数字相加,需要考虑进位问题。 - **LeetCode 21. Merge Two Sorted Lists**:合并两个有序链表。 - **LeetCode 234. Palindrome Linked List**:判断链表是否是回文结构,可以使用快慢指针和反转链表结合的方法[^1]。 ### 树与图类问题 - **LeetCode 104. Maximum Depth of Binary Tree**:计算二叉树的最大深度。 - **LeetCode 102. Binary Tree Level Order Traversal**:二叉树的层序遍历。 - **LeetCode 236. Lowest Common Ancestor of a Binary Tree**:找到二叉树的最近公共祖先。 ### 排列组合与回溯类问题 - **LeetCode 面试题 08.08. 有重复字符串的排列组合**:给出有重复字符串的所有排列组合,通常使用回溯法实现[^5]。 - **LeetCode 46. Permutations**:生成不重复数字的所有排列。 - **LeetCode 78. Subsets**:生成一个数组的所有子集。 ### 动态规划类问题 - **LeetCode 70. Climbing Stairs**:爬楼梯问题,动态规划入门题。 - **LeetCode 198. House Robber**:打家劫舍问题,典型的线性动态规划。 - **LeetCode 322. Coin Change**:找零钱的最小硬币数,典型的完全背包问题。 ### 高频经典题 - **LeetCode 3. Longest Substring Without Repeating Characters**:无重复字符的最长子串,滑动窗口法的经典应用[^3]。 - **LeetCode 5. Longest Palindromic Substring**:最长回文子串,扩展中心法或动态规划解决。 - **LeetCode 8. String to Integer (atoi)**:字符串转换为整数,需考虑各种边界条件。 ### 代码示例 以下是一个判断两个字符串是否互为变位词的 Java 示例代码: ```java class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; int[] num = new int[26]; for (int i = 0; i < s.length(); i++) { num[s.charAt(i) - 'a']++; num[t.charAt(i) - 'a']--; } for (int i : num) { if (i != 0) return false; } return true; } } ``` ### 进阶建议 在准备 LeetCode 面试题时,不仅要掌握这些高频题目,还要理解其背后的数据结构和算法思想,例如快慢指针、双指针、滑动窗口、动态规划等。此外,代码实现要熟练,尤其是链表反转、字符串处理、数组操作等基础操作。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值