zoukankan      html  css  js  c++  java
  • 二叉树的最近公共祖先

    二叉树的最近公共祖先

    题目:
    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

    例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
    https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/binarytree.png
    示例 1:

    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    输出: 3
    解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
    示例 2:

    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    输出: 5
    解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。

    解题思路:用递归解决,递归函数的节点只有几种情况

    1. 节点为null,直接返回null
    2. 节点是p或者q,那就返回该节点
    3. 都不是,就需要判断该节点的左子树或者右子树是否含有p或q
    /**
     * 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) {
            return find(root, p, q);
        }
        
        //如果找到了p或q节点则返回该节点
        private TreeNode find(TreeNode node, TreeNode p, TreeNode q) {
            if(node == null)
                return null;
            
            if(node == p || node == q)
                return node;
            
            TreeNode left = find(node.left, p, q);
            TreeNode right = find(node.right, p, q);
            
            //左右子树都没有p,q
            if(left == null && right == null)
                return null;
            
            //右子树有p,q
            if(left == null && right != null)
                return right;
            
            //左子树有p,q
            if(left != null && right == null)
                return left;
            
            // p,q都在该节点的左右子树那该节点就是最小公共祖先
            return node;
        }
    }
    
  • 相关阅读:
    死锁是什么?如何避免死锁?
    HTTP协议 (二) 基本认证
    HTTP协议
    Fiddler 教程
    Wireshark基本介绍和学习TCP三次握手
    洛谷.4512.[模板]多项式除法(NTT)
    洛谷.4238.[模板]多项式求逆(NTT)
    洛谷.3803.[模板]多项式乘法(NTT)
    UOJ.87.mx的仙人掌(圆方树 虚树)(未AC)
    BZOJ.3991.[SDOI2015]寻宝游戏(思路 set)
  • 原文地址:https://www.cnblogs.com/katoMegumi/p/13919414.html
Copyright © 2011-2022 走看看