File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * function TreeNode(val, left, right) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.left = (left===undefined ? null : left)
6+ * this.right = (right===undefined ? null : right)
7+ * }
8+ */
9+ /**
10+ * @param {TreeNode } root
11+ * @return {TreeNode }
12+ */
13+ const balanceBST = function ( root ) {
14+ const arr = [ ]
15+ inOrder ( root , arr )
16+ return constructBST ( arr , 0 , arr . length - 1 )
17+ } ;
18+
19+ function inOrder ( node , arr ) {
20+ if ( node == null ) return
21+ inOrder ( node . left , arr )
22+ arr . push ( node . val )
23+ inOrder ( node . right , arr )
24+ }
25+
26+ function constructBST ( arr , start , end ) {
27+ if ( start > end ) return null
28+ const mid = start + ( ( end - start ) >> 1 )
29+ const node = new TreeNode ( arr [ mid ] )
30+ node . left = constructBST ( arr , start , mid - 1 )
31+ node . right = constructBST ( arr , mid + 1 , end )
32+ return node
33+ }
You can’t perform that action at this time.
0 commit comments