[leetCode]236. 二叉树的最近公共祖先

递归

思路:
直观的想法是从底向上遍历,如果发现p在当前节点左子树q在当前节点右子树或者p在当前节点右子树,q在当前节点左子树时则说明当前节点是p与q的最小公共祖先。
二叉树的后序遍历正好符合自底向上的遍历条件,因此使用后序遍历。这题由于要使用回溯所以返回值不能为空

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // root为null代表没有发现p与q节点,反之为发现了pq节点
        if (root == p || root == q || root == null) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) return root;
        else if (left == null && right != null) return right;
        else if (left != null && right == null) return left;
        else return null;
    }
}
posted @ 2020-11-03 16:44  消灭猕猴桃  阅读(43)  评论(0编辑  收藏  举报