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

    在这里插入图片描述

    思路

    从根节点开始遍历:

    • 如果当前节点大于p,q 那么p,q的最近公共节点在当前节点的左子树
    • 如果当前节点小于p,q 那么p,q的最近公共节点在当前节点的右子树
    • 如果当前节点的值不满足上述两条要求,那么说明当前节点就是「分岔点」。此时,pp 和 qq 要么在当前节点的不同的子树中,要么其中一个就是当前节点。

    递归

    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if (root.val > p.val && root.val > q.val) 
                return lowestCommonAncestor(root.left, p, q);
            if (root.val < p.val && root.val < q.val) 
                return lowestCommonAncestor(root.right, p, q);
            return root;
        }
    }
    

    循环

    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            TreeNode ancestor = root;
            while (true) {
                if (ancestor.val > p.val && ancestor.val > q.val)
                    ancestor = ancestor.left;
                else if (ancestor.val < p.val && ancestor.val < q.val)
                    ancestor = ancestor.right;
                else 
                    break;
            }
            return ancestor;
        }
    }
    
  • 相关阅读:
    电源积累
    电感的分类及作用
    电容退耦原理分享
    电容选型
    上拉电阻
    LVTTL与LVCMOS区别
    可重入函数与不可重入函数
    永不改变的PCB设计黄金法则
    os_cpu_a.asm
    [原创]Getting Started with Skywalking
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859921.html
Copyright © 2011-2022 走看看