1. 程式人生 > >Find distance between two give node of binary tree

Find distance between two give node of binary tree

ret eth tco method left site println urn print

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