public static TreeNodeWithCount BuildTreeNode(TreeNode root) { if (root == null) { return(null); } TreeNodeWithCount node = new TreeNodeWithCount(root.val); node.left = BuildTreeNode(root.left); node.right = BuildTreeNode(root.right); if (node.left != null) { node.count += node.left.count; } if (node.right != null) { node.count += node.right.count; } return(node); }
public static int helper(TreeNodeWithCount node, int k) { if (node.left != null) { int cnt = node.left.count; if (k <= cnt) { return(helper(node.left, k)); } else if (k > cnt + 1) { return(helper(node.right, k - 1 - cnt)); } return(node.val); } else { if (k == 1) { return(node.val); } return(helper(node.right, k - 1)); } }
public int KthSmallest(TreeNode root, int k) { var tree = TreeNodeWithCount.BuildTreeNode(root); return(TreeNodeWithCount.helper(tree, k)); }