File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -473,6 +473,51 @@ var invertTree = function(root) {
473
473
};
474
474
```
475
475
476
+ C:
477
+ 递归法
478
+ ``` c
479
+ struct TreeNode* invertTree (struct TreeNode* root){
480
+ if(!root)
481
+ return NULL;
482
+ //交换结点的左右孩子(中)
483
+ struct TreeNode* temp = root->right;
484
+ root->right = root->left;
485
+ root->left = temp;
486
+ 左
487
+ invertTree(root->left);
488
+ //右
489
+ invertTree(root->right);
490
+ return root;
491
+ }
492
+ ```
493
+ 迭代法:深度优先遍历
494
+ ```c
495
+ struct TreeNode* invertTree(struct TreeNode* root){
496
+ if(!root)
497
+ return NULL;
498
+ //存储结点的栈
499
+ struct TreeNode** stack = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 100);
500
+ int stackTop = 0;
501
+ //将根节点入栈
502
+ stack[stackTop++] = root;
503
+ //若栈中还有元素(进行循环)
504
+ while(stackTop) {
505
+ //取出栈顶元素
506
+ struct TreeNode* temp = stack[--stackTop];
507
+ //交换结点的左右孩子
508
+ struct TreeNode* tempNode = temp->right;
509
+ temp->right = temp->left;
510
+ temp->left = tempNode;
511
+ //若当前结点有左右孩子,将其入栈
512
+ if(temp->right)
513
+ stack[stackTop++] = temp->right;
514
+ if(temp->left)
515
+ stack[stackTop++] = temp->left;
516
+ }
517
+ return root;
518
+ }
519
+ ```
520
+
476
521
-----------------------
477
522
* 作者微信:[ 程序员Carl] ( https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw )
478
523
* B站视频:[ 代码随想录] ( https://space.bilibili.com/525438321 )
You can’t perform that action at this time.
0 commit comments