您的位置:首页 > 其它

LeetCode 226. Invert Binary Tree 递归、指针交换 思考链表的交换

2017-05-31 14:53 465 查看

226. Invert Binary Tree

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.

题意

给定一个二叉树,按层反转

思路

简化问题,可以这样看问题,整个二叉树可以看做,先交换左子树,再交换右子树,最后再来交换根节点的左右子树。

代码

class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return NULL;

invertTree(root->left);
invertTree(root->right);
swap(root->left,root->right);

return root;
}
};


结果



题外

左右子树能相互交换,受此影响,链表的两个结点交换会发生什么呢

链表:1->2->3->4->5->NULL

ListNode* swaplist(ListNode *head)
{
ListNode* head1 = new ListNode(0);
head1->next = head;
swap(head, head->next);
return head1->next;
}


返回的结果:1->1->1->1->1…陷入环

分析原因



0->1->2->3->4->5->NULL



其实是将结点1的next指针指向了本身。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: