zoukankan      html  css  js  c++  java
  • Find distance between two give node of binary tree

    Dis(n1, n2) = Dis(root, n1) + Dis(root, n2) - 2* Dis(root, lca)

    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		onsite2 onsite2=new onsite2();
    		TreeNode root = new TreeNode(5);
    		root.left = new TreeNode(10);
    		root.right = new TreeNode(15);
    		root.left.left = new TreeNode(20);
    		root.left.right = new TreeNode(25);
    		root.right.left = new TreeNode(30);
    		root.right.right = new TreeNode(35);
    		root.left.right.right = new TreeNode(45);
    		
    	
    		System.out.println("Distance between 45 and 20 is : "
    				+ 	onsite2.findDistance(root,15,45));
    	}
    
    	public int findDistance(TreeNode root, int n1, int n2) {
    		int x = Pathlength(root, n1) - 1;
    		int y = Pathlength(root, n2) - 1;
    		int lcaData = lowestCommonAncestor(root, n1, n2).val;
    		int lcaDistance = Pathlength(root, lcaData) - 1;
    		return (x + y) - 2 * lcaDistance;
    	}
    	
    	public int Pathlength(TreeNode root, int n1) {
    		if (root != null) {
    			int x = 0;
    			if ((root.val == n1) || (x = Pathlength(root.left, n1)) > 0
    					|| (x = Pathlength(root.right, n1)) > 0) {
    				// System.out.println(root.data);
    				return x + 1;
    			}
    			return 0;
    		}
    		return 0;
    	}
    	 public TreeNode lowestCommonAncestor(TreeNode root, int p, int q)
    	 {
    		 if (root==null ||root.val==p|| root.val==q) {
    			return root;
    		}
    		 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;
    	 }
    

      

  • 相关阅读:
    钩子函数和回调函数
    Vue.js的坑
    数据库清空表中的数据
    chrome jsonView插件安装
    PostgreSQL数据的导出导入
    PostgreSQL9.6.2的WINDOWS下安装
    HEXO+Github,搭建属于自己的博客
    Vue.js 入门指南之“前传”(含sublime text 3 配置)
    win系统下nodejs安装及环境配置
    Vue.js学习网址
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/7500086.html
Copyright © 2011-2022 走看看