Find distance between two given keys of a Binary Tree
Anonymous
public int getNodeDistance(TreeNode a, TreeNode b, TreeNode root){ if(root == null) { return 0; } int aHeight = getHeight(root, a, 0); int bHeight = getHeight(root, b, 0); return aHeight + bHeight; } public int getHeight(TreeNode root, TreeNode a, int level){ if(root == null) return 0; if(root == a) return level; int left = getHeight(root.left, a, level+1) ; if(left != 0) return left; int right = getHeight(root.right, a, level+1); return right; }
Check out your Company Bowl for anonymous work chats.