zoukankan      html  css  js  c++  java
  • LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)

    Lowest Common Ancestor of a Binary Search Tree

    一、题目描写叙述

    这里写图片描写叙述

    二、思路及代码

    二叉搜索树有个性质:左子树的值都比根节点小,右子树的值比根节点大。那么我们的思路就是递归比較。
    假设输入的两个节点的值比当前节点小,说明是在当前根节点的左子树中;反之则在右子树中。

    假设当前根节点比一个大。比一个小。那么第一个出现的这种节点就是近期的父亲节点了。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public 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);
            }else if(root.val < p.val && root.val < q.val){
                return lowestCommonAncestor(root.right, p, q);
            }else{
                return root;
            }
        }
    }

    Lowest Common Ancestor of a Binary Tree

    一、题目描写叙述

    这里写图片描写叙述

    二、思路及代码

    假设是普通的二叉树。没有了二叉搜索树的特性。就要遍历;于是我们用到DFS遍历树

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root == null || root == p || root == q) return root; //找到p或者q节点,或者到最底层的叶子节点时,返回;
            TreeNode left = lowestCommonAncestor(root.left, p, q);
            TreeNode right = lowestCommonAncestor(root.right, p, q);
    
            if(left != null && right != null) return root; //找到了父节点
            return left != null ?

    left : right; //所以假设都未找到,返回null } }

  • 相关阅读:
    【python】requests库
    pycharm新建项目时选择virtualenv的说明
    cookie、session、token
    读写锁--DEMO
    锁降级--防止线程安全问题
    mysql-left join
    index-document-shard
    ES-常见搜索方式
    SpringBoot在自定义类中调用service层等Spring其他层
    mongodb crud
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7221089.html
Copyright © 2011-2022 走看看