[编程题] lc[236. 二叉树的最近公共祖先]

[编程题] lc:236. 二叉树的最近公共祖先

题目描述

image-20200718230220495

输入输出例子

image-20200718230251908

思路

使用后续遍历的思想,根据找到了左和右的情况,进行相应的返回结果。

Java代码

/**
 * 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);
       //上边得到了当前root的左右子树,判断情况,我们就知道我们返回什么。
       //如果左边没有任何p,q,那直接返回right节点是一定能找到的
       if(left==null){
           return right;
       }
       if(right==null){
           return left;//类似原理
       }
       //如果左右都不为空,那么root节点就是公共祖先
       if(left!=null && right!=null){
           return root;
       }else{
           return null;
       }    

   }
}
posted @ 2020-07-18 23:06  北鼻coder  阅读(127)  评论(0编辑  收藏  举报