首页 > 其他 > 详细

236. Lowest Common Ancestor of a Binary Tree

时间:2018-10-24 10:20:30      阅读:99      评论:0      收藏:0      [点我收藏+]

 

 

 1 //New
 2 class Solution {
 3     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
 4         if(root == null) return null;
 5         if(root.val == p.val || root.val == q.val){
 6             return root;
 7         }
 8         TreeNode left = lowestCommonAncestor(root.left, p, q);
 9         TreeNode right = lowestCommonAncestor(root.right, p, q);
10         if(left != null && right != null){
11             return root;
12         }else{
13             return (left != null ? left : right);
14         }
15         
16     }
17 }

 

 

 1 class Solution {
 2     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
 3         if(root == null || p == null || q == null) return null;
 4         if(root.val == p.val || root.val == q.val) return root;
 5         boolean f1 = false, f2 = false;
 6         f1 = dfs(root.left, p) || dfs(root.left, q);
 7         f2 = dfs(root.right, p) || dfs(root.right, q);
 8         if(f1 && f2){
 9             return root;
10         }else if(f1){
11             return lowestCommonAncestor(root.left, p, q);
12         }else if(f2){
13             return lowestCommonAncestor(root.right, p, q);
14         }
15         return null;
16         
17     }
18     
19     public boolean dfs(TreeNode root, TreeNode node){
20         if(root == null) return false;
21         if(root.val == node.val) return true;
22         return dfs(root.left, node) || dfs(root.right, node);
23     }
24     
25 }

 

236. Lowest Common Ancestor of a Binary Tree

原文:https://www.cnblogs.com/goPanama/p/9841558.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!