zoukankan      html  css  js  c++  java
  • 剑指 Offer 68

    /**
     * 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 leftNode = lowestCommonAncestor(root.left,p,q);
            TreeNode rightNode = lowestCommonAncestor(root.right,p,q);
    
            //1、root 的 左右子树都不包含p、q,返回null
            if(leftNode == null && rightNode == null) return null;
            //2、p、q分列 root的左、右子树中。因此root是最近公共祖先,返回root
            if(leftNode != null && rightNode != null) return root;//多余了
            //3、左子树为空,右子树不为空,说明p、q都在右子树中,返回right
            if(leftNode == null && rightNode != null) return rightNode; // if(leftNode == null) return rightNode;
            //4、同3
            if(leftNode != null && rightNode == null) return leftNode;  // if(rightNode == null) return leftNode;
            return root;
        }
    }
  • 相关阅读:
    第二章—数据类型字符串str
    第二章—数据类型列表list
    第二章—编码
    第二章——进制
    ConfigParser模块
    描述符__get__,__set__,__delete__
    面向对象 ,特殊成员和魔法方法
    异常处理
    反射
    绑定方法与非绑定方法
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14154217.html
Copyright © 2011-2022 走看看