[LeetCode]236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:淘宝开店宝软件 编辑:程序博客网 时间:2024/05/19 19:57
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
找出两个节点的公共祖先,树是普通二叉树
lowestCommonAncestor找在root为根节点的子树上遍历到的第一个p或者q,如果两个都遍历到就返回root,如果p和q都不在这个子树上就返回null,否则返回p和q里面先遍历到的那个。因此如果left和right都不是null,那么就返回root
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); return left == null ? right : right == null ? left : root; }}
0 0
- [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
- Leetcode-236. Lowest Common Ancestor of a Binary Tree
- 3D游戏引擎系列六
- Cookie中保存中文出错HTTP Status 500-
- Kali安装笔记20170202
- 最近一段时间的总结
- 带验证码的HTML5登陆页面
- [LeetCode]236. Lowest Common Ancestor of a Binary Tree
- unity中简单的js脚本
- <!DOCTYPE html>很重要
- 基于openstack构建私有云实践
- java获取mysql表结构
- 面向小数据集构建图像分类模型
- [Codeforces Round #373 DIV1C (CF718C)] Sasha and Array
- 《剑指offer》--- 在O(1)时间内删除链表结点 和 调整数组顺序使得奇数位于偶数前面
- Codeforces Round #394 (Div. 2) Dasha and Very Difficult Problem