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

      

  • 相关阅读:
    安装IIS的郁闷之旅
    设置WPF窗口相对于非WPF窗口的位置
    钓鱼记
    java拾遗
    人间四月芳菲尽
    [linux] x server can not start under VMWare
    如果没有开源软件没有免费软件,这个世界会怎么样?评[盖茨北大演讲遭遇开源人士抗议]
    程序员的面包
    2007中国软件英雄会-七年的等待
    sysbench安装
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/7500086.html
Copyright © 2020-2023  润新知