码迷,mamicode.com
首页 > 其他好文 > 详细

236. Lowest Common Ancestor of a Binary Tree

时间:2018-10-24 10:43:58      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:turn   common   pre   boolean   tor   val   bool   null   nan   

 

 

 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

标签:turn   common   pre   boolean   tor   val   bool   null   nan   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!