Created
April 2, 2014 02:19
-
-
Save rayjcwu/9926916 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
Node left; | |
Node right; | |
int treeSize; | |
int val; | |
} | |
public float getMedian(Node root) { | |
if (root == null) { | |
return 0; // not sure how you want to handle empty tree | |
} | |
final int N = root.treeSize; | |
if (N % 2 == 0) | |
return 0.5 * (findKth(root, N / 2) + findKth(root, N / 2 + 1)); | |
else | |
return (float) findKth(root, N / 2 + 1); | |
} | |
public int findKth(Node n, int k) { | |
final int leftSize = (n.left == null) ? 0: n.left.TreeSize; | |
if (leftSize == k - 1) { | |
return n.val; | |
} else if (leftSize > k) { | |
return findKth(n.left, k); | |
} else { | |
return findKth(n.right, k - 1 - leftSize); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment