Thought:
It is a little tricky that we should keep flag to track the Node to be used as current root.
Whenever we call build, flag will go ahead by one Node, so that it always points at the new node.
Code:
public class Solution {
public static ListNode flag = null;
public TreeNode sortedListToBST(ListNode head) {
int size = 0;
flag = head;
while(head != null) {
size++;
head = head.next;
}
return build(size);
}
public TreeNode build(int size) {
if(size <= 0) {
return null;
}else{
TreeNode left = build(size / 2);
TreeNode root = new TreeNode(flag.val);
flag = flag.next;
root.left = left;
root.right = build(size - 1 - size / 2);
return root;
}
}
}
Keep in Mind that Flag must be a static, because we want flag go ahead every time we run build.
ReplyDeleteflag's heading should be visible out of build method instead of within it.