Skip to content

Commit 5709c32

Browse files
authored
Create 156-binary-tree-upside-down.md
1 parent 2d6fed5 commit 5709c32

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
![alt text](https://github.com/everthis/leetcode-js/blob/master/images/binary-tree-upside-down.webp "binary-tree-upside-down")
2+
3+
```js
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val) {
7+
* this.val = val;
8+
* this.left = this.right = null;
9+
* }
10+
*/
11+
/**
12+
* @param {TreeNode} root
13+
* @return {TreeNode}
14+
*/
15+
const upsideDownBinaryTree = function(root) {
16+
let curr = root
17+
let next = null
18+
let temp = null
19+
let prev = null
20+
while (curr !== null) {
21+
next = curr.left
22+
curr.left = temp
23+
temp = curr.right
24+
curr.right = prev
25+
prev = curr
26+
curr = next
27+
}
28+
return prev
29+
}
30+
31+
// another
32+
33+
const upsideDownBinaryTree = function(root) {
34+
if (root == null || root.left == null) {
35+
return root
36+
}
37+
const newRoot = upsideDownBinaryTree(root.left)
38+
root.left.left = root.right
39+
root.left.right = root
40+
root.left = null
41+
root.right = null
42+
return newRoot
43+
}
44+
```

0 commit comments

Comments
 (0)