首页 > 其他 > 详细

【07_226】Invert Binary Tree

时间:2015-12-13 12:29:38      阅读:249      评论:0      收藏:0      [点我收藏+]

Invert Binary Tree

Total Accepted: 54994 Total Submissions: 130742 Difficulty: Easy

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9
to
     4
   /     7     2
 / \   / 9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

 
 
通过这道题,好好理解了递归。
递归返回的是什么要考虑清楚,
可以仔细研磨这道题,很好的题。
 
 
C语言
 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)
11         return root;
12     if (root->left == NULL && root->right == NULL)
13         return root;
14     else{
15         struct TreeNode* temp = root->right;
16         root->right = root->left;
17         root->left = temp;
18     }
19     root->left = invertTree(root->left);
20     root->right = invertTree(root->right);
21     
22     return root;
23 }

 

 

下面是在网上找的一种解法,C++写的。由于这是对实际树的结构进行操作,所以说可以不特别管返回值。

1 TreeNode* invertTree(TreeNode* root) {
2     if (root) {
3         invertTree(root->left);
4         invertTree(root->right);
5         std::swap(root->left, root->right);
6     }
7     return root;
8 }

 

【07_226】Invert Binary Tree

原文:http://www.cnblogs.com/QingHuan/p/5042502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!