Skip to content

Commit d8603ed

Browse files
committed
0226.翻转二叉树的JavaScript版本
1 parent 6bdfab2 commit d8603ed

File tree

1 file changed

+92
-2
lines changed

1 file changed

+92
-2
lines changed

problems/0226.翻转二叉树.md

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,10 +247,100 @@ func invertTree(root *TreeNode) *TreeNode {
247247
}
248248
```
249249

250-
250+
JavaScript:
251+
252+
使用递归版本的前序遍历
253+
```javascript
254+
var invertTree = function(root) {
255+
//1. 首先使用递归版本的前序遍历实现二叉树翻转
256+
//交换节点函数
257+
const inverNode=function(left,right){
258+
let temp=left;
259+
left=right;
260+
right=temp;
261+
//需要重新给root赋值一下
262+
root.left=left;
263+
root.right=right;
264+
}
265+
//确定递归函数的参数和返回值inverTree=function(root)
266+
//确定终止条件
267+
if(root===null){
268+
return root;
269+
}
270+
//确定节点处理逻辑 交换
271+
inverNode(root.left,root.right);
272+
invertTree(root.left);
273+
invertTree(root.right);
274+
return root;
275+
};
276+
```
277+
使用迭代版本(统一模板))的前序遍历:
278+
```javascript
279+
var invertTree = function(root) {
280+
//我们先定义节点交换函数
281+
const invertNode=function(root,left,right){
282+
let temp=left;
283+
left=right;
284+
right=temp;
285+
root.left=left;
286+
root.right=right;
287+
}
288+
//使用迭代方法的前序遍历
289+
let stack=[];
290+
if(root===null){
291+
return root;
292+
}
293+
stack.push(root);
294+
while(stack.length){
295+
let node=stack.pop();
296+
if(node!==null){
297+
//前序遍历顺序中左右 入栈顺序是前序遍历的倒序右左中
298+
node.right&&stack.push(node.right);
299+
node.left&&stack.push(node.left);
300+
stack.push(node);
301+
stack.push(null);
302+
}else{
303+
node=stack.pop();
304+
//节点处理逻辑
305+
invertNode(node,node.left,node.right);
306+
}
307+
}
308+
return root;
309+
};
310+
```
311+
使用层序遍历:
312+
```javascript
313+
var invertTree = function(root) {
314+
//我们先定义节点交换函数
315+
const invertNode=function(root,left,right){
316+
let temp=left;
317+
left=right;
318+
right=temp;
319+
root.left=left;
320+
root.right=right;
321+
}
322+
//使用层序遍历
323+
let queue=[];
324+
if(root===null){
325+
return root;
326+
}
327+
queue.push(root);
328+
while(queue.length){
329+
let length=queue.length;
330+
while(length--){
331+
let node=queue.shift();
332+
//节点处理逻辑
333+
invertNode(node,node.left,node.right);
334+
node.left&&queue.push(node.left);
335+
node.right&&queue.push(node.right);
336+
}
337+
}
338+
return root;
339+
};
340+
```
251341

252342
-----------------------
253343
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
254344
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
255345
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
256-
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
346+
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

0 commit comments

Comments
 (0)