Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:虚拟机 ubuntu 屏幕 编辑:程序博客网 时间:2024/04/30 06:08
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
题目大意:已知一个BST,找到BST中的节点p+q的最小公共祖先;
思路:递归
1 boundary conditions: tree, p, q任意为null, 返回null
2 如果p.va, q.val均小于root.val -> 说明p,q都在左子树-> return LowestCommonAncestor(root.left, p, q);
3 如果p.va, q.val均大于root.val -> 说明p,q都在右子树-> return LowestCommonAncestor(root.right, p, q);
4 否则,说明一左一右->root即为最小公共祖先
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (p == null || q == null || root == null) { return null; } if (p.val < root.val && q.val < root.val) { return LowestCommonAncestor(root.left, p, q); } else if (p.val > root.val && q.val > root.val) { return LowestCommonAncestor(root.right, p, q); } else { return root; } }
0 0
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- leetcode:235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode *** 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode-235.Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode-235. Lowest Common Ancestor of a Binary Search Tree
- 235.[Leetcode]Lowest Common Ancestor of a Binary Search Tree
- 【leetcode】235. Lowest Common Ancestor of a Binary Search Tree
- 2010华科金融女清华计算机
- zzzzzz
- 生疏的两种排序算法——堆、归并排序
- 再见广州,京城我回来了
- [leetcode] 404. Sum of Left Leaves 解题报告
- Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 408. Valid Word Abbreviation 解题报告
- [leetcode] 409. Longest Palindrome 解题报告
- Leetcode 236. Lowest Common Ancestor of a Binary Tree
- C# POST
- [leetcode] 415. Add Strings 解题报告
- 从栈的分配例子来看malloc分配内存的问题
- [leetcode] 416. Partition Equal Subset Sum 解题报告
- C语言的布尔类型bool