给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
例:图中给定树 {3,5,1,6,2,0,8,#,#,7,4} 中,节点6、节点4的最近公共祖先为5。
class Solution: def nearestCommonAncestor(self , root , p , q ): # write code here if not root&nbs***bsp;root.val == q.val&nbs***bsp;root.val == p.val: return root left = self.nearestCommonAncestor(root.left, p, q) right = self.nearestCommonAncestor(root.right, p, q) if not left: return right if not right: return left return root
简单题
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param p TreeNode类
* @param q TreeNode类
* @return TreeNode类
*/
public TreeNode nearestCommonAncestor (TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root.val == p.val || root.val == q.val) {
return root;
}
TreeNode leftAns = nearestCommonAncestor(root.left, p, q),
rightAns = nearestCommonAncestor(root.right, p, q);
if (leftAns != null && rightAns != null) {
return root;
}
return leftAns != null ? leftAns : rightAns;
}
}
public class Solution {
/**
*
* @param root TreeNode类
* @param p TreeNode类
* @param q TreeNode类
* @return TreeNode类
*/
public TreeNode nearestCommonAncestor (TreeNode root, TreeNode p, TreeNode q) {
// write code here
return helper(root, p, q);
}
public TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (root.val == p.val || root.val == q.val)
return root;
TreeNode left = helper(root.left, p, q), right = helper(root.right, p, q);
if (left == null && right == null)
return null;
else if (left != null && right != null)
return root;
else
return left == null ? right : left;
}
}