Simple JAVA solution use DFS


  • 0
    D
    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            List<Integer> res = new ArrayList<>();
            while (head != null){
                res.add(head.val);
                head = head.next;
            }
            return fun(res,0,res.size()-1);
        }
        public TreeNode fun(List<Integer> list,int l,int r){
            if (l > r) return null;
            int index = (l + r)/2;
            TreeNode root = new TreeNode(list.get(index));
            root.left = fun(list,l,index - 1);
            root.right = fun(list,index + 1,r);
            return root;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.