数据结构:二叉树
算法:二叉树的先序遍历,先判断根结点是不是空或者最近祖先,不是则递归遍历左子树,判断左子树是不是空或是最近祖先,再递归判断右子树是不是空或者最近祖先。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q)
return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left == null)
return right;
if(right == null)
return left;
return root;
}
}
留个眼,这题做了几次还是忘记,说明理解不深刻。