LeetCode 226 Invert Binary Tree 题解

题意

翻转一棵二叉树,例如将

1
2
3
4
5
4
/ \
2 7
/ \ / \
1 3 6 9

翻转为

1
2
3
4
5
4
/ \
7 2
/ \ / \
9 6 3 1

分析

思路非常简单,递归地翻转所有子树即可。在马桶上用iPad一次刷过了此题。直接上代码。

C代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
struct TreeNode *temp;
if(root == NULL) return NULL;
if(root->left) invertTree(root->left);
if(root->right) invertTree(root->right);
temp = root->left;
root->left = root->right;
root->right = temp;
return root;
}

版权声明

The Bloom of Youth by KUANG Qi is licensed under a Creative Commons BY-NC-ND 4.0 International License.
况琪创作并维护的锦瑟华年博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于The Bloom of Youth | 锦瑟华年博客( http://kuangqi.me ),版权所有,侵权必究。

本文永久链接:http://kuangqi.me/programming/leetcode-invert-binary-tree/