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;
    	 }
    

      

  • 相关阅读:
    数据库复习笔记
    mysql基础实验过程+遇到的问题的解决方法(error105处理)
    R文件变红原因to按钮变色的优化
    windos命令行设置网络
    牛客网-21天刷题计划-第2节 进阶-对称的二叉树
    0型文法、1型文法、2型文法、3型文法对照
    ES练习遇到错误
    安装kafka
    使用ES时踩过的坑
    前端报错
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/7500086.html
Copyright © 2011-2022 走看看