LeetCode:M-236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:淘宝个人店铺 发票 编辑:程序博客网 时间:2024/06/03 21:34
LeetCode链接
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、判断当前node是否等于p,q,若相等,则当前node为目前p or q 的最近father(其实不应该这样,应该是前一个,但是题目中实验发现,同一边的p和q,LCA为第一个发现的p or q)
2、若当前节点的左右都找到了p/q中的一个node,则当前节点是LCA
3、否则LCA为任一个不为null的left or right(即使两者均为null,最后的返回式也成立)
/** * 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; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left!=null && right!=null) return root; return left!=null?left:right; }}
- LeetCode:M-236. Lowest Common Ancestor of a Binary Tree
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236.Lowest Common Ancestor of a Binary Tree
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236. Lowest Common Ancestor of a Binary Tree
- 236. Lowest Common Ancestor of a Binary Tree LeetCode
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree
- leetcode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode-236.Lowest Common Ancestor of a Binary Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode *** 236. Lowest Common Ancestor of a Binary Tree
- leetcode.236. Lowest Common Ancestor of a Binary Tree
- LeetCode - 236. Lowest Common Ancestor of a Binary Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- [LeetCode] 236. Lowest Common Ancestor of a Binary Tree
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree
- Leetcode 236. Lowest Common Ancestor of a Binary Tree
- Leetcode 236. Lowest Common Ancestor of a Binary Tree
- 利用自动化铺平Devops之路
- Hibernate与MyBatis的对比总结
- Python三元运算符替代方案
- 【HDU6198 2017 ACM ICPC Asia Regional Shenyang Online E】【找规律 + 矩阵快速幂 + 粗略证明】number number number 无法用K
- Installation failed with message INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries
- LeetCode:M-236. Lowest Common Ancestor of a Binary Tree
- formdata
- JavaWeb网页聊天室(WebSocket即时通讯)
- 堆排序
- leetcode485. Max Consecutive Ones
- Java单例模式
- GBDT(sklearn)进行回归
- Getmemory函数详解--内存操作的理解
- 大数据知识体系