LeetCode 226. 翻转二叉树

题目链接:https://leetcode-cn.com/problems/invert-binary-tree/

翻转一棵二叉树。

示例:

输入:

4
/ \
2 7
/ \ / \
1 3 6 9
输出:

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

我写的:

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

官方解法:

1 struct TreeNode* invertTree(struct TreeNode* root){
2     if(root==NULL) return root;
3     struct TreeNode *right = invertTree(root->right);
4     struct TreeNode *left = invertTree(root->left);
5     root->left = right;
6     root->right = left;
7     return root;
8 }

 

posted @ 2019-08-16 14:42  wydxry  阅读(275)  评论(0编辑  收藏  举报
Live2D