二叉树最近公共祖先

思路:后序遍历

分情况讨论:

1、两个节点在根的左侧

2、两个节点在根的右侧

3、两个节点在根的左右两侧

/**
 * 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==q||root==p||root == null) return root;//找到或者没找到都进行返回继续递归
        TreeNode l = lowestCommonAncestor(root.left,p,q);
        TreeNode r = lowestCommonAncestor(root.right,p,q);
        if(l==null) return r;//两个节点都不在左子树
        if(r==null) return l;//两个节点都不在右子树
        return root;//两个节点一左一右
    }
}

猜你喜欢

转载自www.cnblogs.com/cstdio1/p/13367727.html