zoukankan      html  css  js  c++  java
  • [编程题] 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;
           }    
    
       }
    }
    
  • 相关阅读:
    maven 常用命令
    navicat 破解
    linux命令
    Git常用命令
    关于近期工作的总结
    ES6新特性学习
    Hadoop初步学习
    串行、并行与并发的理解
    通过Spring profile方式实现多环境部署
    使用MySQL乐观锁解决超卖问题
  • 原文地址:https://www.cnblogs.com/jiyongjia/p/13338026.html
Copyright © 2011-2022 走看看