zoukankan      html  css  js  c++  java
  • [LeetCode] Lowest Common Ancestor of a Binary Search Tree

    Well, remember to take advantage of the property of binary search trees, which is, node -> left -> val < node -> val < node -> right -> val. Moreover, both p and q will be the descendants of the root of the subtree that contains both of them. And the root with the largest depth is just the lowest common ancestor. This idea can be turned into the following simple recursive code.

     1 class Solution {
     2 public:
     3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     4         if (p -> val < root -> val && q -> val < root -> val)
     5             return lowestCommonAncestor(root -> left, p, q);
     6         if (p -> val > root -> val && q -> val > root -> val)
     7             return lowestCommonAncestor(root -> right, p, q);
     8         return root;
     9     }
    10 };

    Of course, we may also solve it iteratively.

     1 class Solution {
     2 public:
     3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     4         TreeNode* cur = root;
     5         while (true) {
     6             if (p -> val < cur -> val && q -> val < cur -> val)
     7                 cur = cur -> left;
     8             else if (p -> val > cur -> val && q -> val > cur -> val)
     9                 cur = cur -> right;
    10             else return cur;
    11         }
    12     }
    13 };
  • 相关阅读:
    Python进阶06 循环对象
    Python进阶05 循环设计
    Python进阶 函数的参数对应
    Python进阶01 词典
    Python基础 反过头来看看
    Python基础08 面向对象的基本概念
    利用zepto.js实现移动页面图片全屏滑动
    数组弃重方法
    fcc筆記
    文字颜色渐变效果
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4638519.html
Copyright © 2011-2022 走看看