zoukankan      html  css  js  c++  java
  • 8888. Distance Between 2 Nodes in BST

    Write a function that given a BST, it will return the distance (number of edges) between 2 nodes.

    For example, given this tree

             5
            / 
           3   6
          /    
         2   4   7
        /         
       1           8
    

    The distance between 1 and 4 is 3: [1 -> 2 -> 3 -> 4]

    The distance between 1 and 8 is 6: [1 -> 2 -> 3 -> 5 -> 6 -> 7 -> 8]

    public int bstDistance(TreeNode root, int node1, int node2) {
        if (root == null) return -1;
        TreeNode lca = lca(root, node1, node2);
        return getDistance(lca, node1) + getDistance(lca, node2);
    }
    
    private int getDistance(TreeNode src, int dest) {
        if (src.val == dest) return 0;
        TreeNode node = src.left;
        if (src.val < dest) {
            node = src.right;
        }
        return 1 + getDistance(node, dest);
    }
    
    private TreeNode lca(TreeNode root, int node1, int node2) {
        while (true) {
            if (root.val > node1 && root.val > node2) {
                root = root.left;
            } else if (root.val < node1 && root.val < node2) {
                root = root.right;
            } else {
                return root;
            }
        }
    }

    Java solution:
    Time complexity: O(h), where h is the height of the tree.
    Space complexity: O(h).

    找到LCA---计算LCA到两个node的距离并相加

    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);//尝试在左边找p和q
            TreeNode right = lowestCommonAncestor(root.right, p, q);//尝试在右边找q和q
            
            if(left != null && right != null) return root;//如果p、q在左右两侧,说明root是LCA
            
            return left != null ? left : right;
            //如果p和q都在右边(left == null)就返回right,right会返回p和q中首先发现的,就一定是LCA了
            //如果p和q都在左边(right == null),和上面情况类似。
        }
    }

    lca的另一种查找方法

    static int distanceFromRoot(Node root, int x)  
    {  
        if (root.key == x)  
            return 0;  
        else if (root.key > x)  
            return 1 + distanceFromRoot(root.left, x);  
        return 1 + distanceFromRoot(root.right, x);  
    }  

    计算distance的另一种写法

  • 相关阅读:
    查看JVM
    性能测试 -- 实际问题
    性能测试 -- 常用命令
    性能测试 -- 实际例子
    性能测试 -- 内核调优
    jmeter分布式环境
    Linux 安装配置Subversion edge
    Jenkins进阶系列之——01使用email-ext替换Jenkins的默认邮件通知
    Ubuntu下eclipse安装svn插件
    Jenkins入门系列之——03PDF文档下载
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13445694.html
Copyright © 2011-2022 走看看