Find distance between two give node of binary tree

Posted lilyfindjob

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
	 }

  

以上是关于Find distance between two give node of binary tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode | 1385. Find the Distance Value Between Two Arrays两个数组间的距离值Python

Finding distance between two curves

[SimHash] find the percentage of similarity between two given data

1184. Distance Between Bus Stops

783. Minimum Distance Between BST Nodes

LeetCode --- 1184. Distance Between Bus Stops 解题报告