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指针指向了本身。
相关文章推荐
- ※ Leetcode - Tree - 226. Invert Binary Tree(反转二叉树 使用二级指针交换两个指针的地址)
- leetcode-226. Invert Binary Tree 二叉树、递归,交换两个变量的值
- 226. Invert Binary Tree -- 二叉树、递归、交换、栈
- leetcode 226. Invert Binary Tree(C语言,二叉树,递归)54
- leetcode 226. Invert Binary Tree | DFS 递归转迭代
- LeetCode (226):Invert Binary Tree 递归实现
- Leetcode 226: Invert Binary Tree(二叉树反转 递归、非递归实现)
- 226.leetcode Invert Binary Tree(easy)[二叉树 递归]
- leetcode 226. Invert Binary Tree(递归)
- [leetcode-226]Invert Binary Tree(c++)
- Leetcode_226 Invert Binary Tree
- [leetcode] 226.Invert Binary Tree
- 【LeetCode】226 - Invert Binary Tree
- [Leetcode 226, Easy] Invert Binary Tree
- LeetCode226——Invert Binary Tree
- LeetCode Solution 05: 226Invert Binary Tree
- LeetCode 226. Invert Binary Tree
- leetcode 226 :Invert Binary Tree
- leetcode 226: Invert Binary Tree
- leetcode 226 Invert Binary Tree 翻转二叉树