236. Lowest Common Ancestor of a Binary Tree最长公共祖先
来源:互联网 发布:2016年coc双王数据 编辑:程序博客网 时间:2024/05/29 14:42
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.
Hide Similar Problems
题目大意:
给一个二叉树,指定其中的两个节点,寻找他们的最近公共祖先。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度,且允许节点是自己本身的父节点。
如5,1的公共祖先节点是3;5,4的公共祖先节点是5.
代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public 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; }else if(left != null) { return left; }else { return right; } }}
0 0
- 236. Lowest Common Ancestor of a Binary Tree最长公共祖先
- 最低公共祖先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 最小公共祖先
- Lowest Common Ancestor of a Binary Search Tree 递归寻找二叉查找树公共祖先
- Lowest Common Ancestor of a Binary Tree 二叉树的公共祖先
- Lowest Common Ancestor of a Binary Search Tree(二叉树最小公共祖先)
- [Leetcode] Lowest Common Ancestor of a Binary Tree 最小公共祖先
- 【二叉树】最近公共祖先Lowest Common Ancestor of a Binary Tree
- 【二叉树】最近公共祖先【235. Lowest Common Ancestor of a Binary Search Tree】
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 最近公共祖先 + BST
- leetcode之二叉树类之最小公共祖先-----236/235. Lowest Common Ancestor of a Binary/Binary Search Tree
- leetcode 236. Lowest Common Ancestor of a Binary Tree 最近公告祖先LCA + 二叉树
- 二叉搜索树(BST)的最近公共祖先(LCA)问题(Lowest Common Ancestor of a Binary Tree)
- [Java]寻找最低公共祖先(排序二叉树)Lowest Common Ancestor of a Binary Search Tree
- [Java]寻找最低公共祖先(普通树的情形)Lowest Common Ancestor of a Binary Tree
- 二叉树中两个结点的最近公共祖先(Lowest Common Ancestor of a Binary Tree)
- LeetCode 235 Lowest Common Ancestor of a Binary Search Tree(二叉搜索树的最小公共祖先)
- hdu 1251 统计难题(字典树)
- HDFS Short-Circuit Local Reads
- docker
- POJ 2488 A Knight's Journey【DFS + 回溯】
- 水仙花数的PE!!!
- 236. Lowest Common Ancestor of a Binary Tree最长公共祖先
- 【a502】符号三角形问题
- (转)adb操作命令详解及大全
- uboot-cmd按键退出
- Ansible最佳实践
- C语言实验——拍皮球 (sdut oj)
- 开始全新的旅程
- three.js之照相机(Camera)
- Darwin分析经验