226. Invert Binary Tree
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9to
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指针指向了本身。