236. Lowest Common Ancestor of a Binary Tree

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

题目含义:求一个普通二叉树中两个节点的最小公共父节点

 

1     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
2         if (root == null || p == root || q == root) return root;
3         TreeNode left = lowestCommonAncestor(root.left, p, q);
4         TreeNode right = lowestCommonAncestor(root.right, p , q);
5         if (left!=null && right!=null) return root;  //p和q与root的左右子节点相等,那么root即为p和q的公共父节点
6         return left!=null ? left : right;//p和q至少有一个为空,表示p和q落在了root的同一侧子树中,所以应该返回不为空的那个子树节点     
7     }

 类似题目:235. Lowest Common Ancestor of a Binary Search Tree

posted @   daniel456  阅读(119)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示