Leetcode 236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:虚拟机 ubuntu 屏幕 编辑:程序博客网 时间:2024/04/30 06:33
原题:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
题目大意:已知一个BT,找到BST中的节点p+q的最小公共祖先;
例子:
_______3______
/ \___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
5,1 -> 3
5,4 -> 5 (允许一个node成为自己的descendant)
思路:
1 boundary conditions: root, p, q任意为null, 返回null
2 查看左子树中是否有目标结点,没有为null
3 都不为空,说明做右子树都有目标结点,则公共祖先就是本身
4 如果有一个为null, 返回另外一个;用三目表达式;
/** * 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 class Solution { public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { //发现目标节点则通过返回值标记该子树发现了某个目标结点 if(root == null || root == p || root == q) return root; //查看左子树中是否有目标结点,没有为null TreeNode left = LowestCommonAncestor(root.left, p, q); //查看右子树是否有目标节点,没有为null TreeNode right = LowestCommonAncestor(root.right, p, q); //都不为空,说明做右子树都有目标结点,则公共祖先就是本身 if(left!=null&&right!=null) return root; //如果发现了目标节点,则继续向上标记为该目标节点 return left == null ? right : left; }}
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
- 再见广州,京城我回来了
- [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
- windows安装clapack
- Maven Pom 文件中的隐式依赖导致Jar冲突
- 小菜鸟用visual studio写c++的种种