Skip to content

Commit 6bd8c4a

Browse files
committed
不递归版本
1 parent 75af833 commit 6bd8c4a

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

leetcode/invert-binary-tree.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,26 @@ var invertTree = function(root) {
4040
}
4141
return root;
4242
};
43+
44+
45+
// 不递归版本
46+
var invertTree = function(root) {
47+
if (root !== null) {
48+
var nodes = [root];
49+
while(nodes.length) {
50+
//将数组中第一个值抛出来,node做对象引用
51+
var node = nodes.shift();
52+
if(node === null) continue;
53+
54+
//放进数组中继续遍历子节点,全部做左右交换
55+
nodes.push(node.left);
56+
nodes.push(node.right);
57+
58+
//交换左右树
59+
node.right = [node.left, node.left = node.right][0];
60+
61+
}
62+
}
63+
64+
return root;
65+
};

0 commit comments

Comments
 (0)