※ Leetcode - Tree - 226. Invert Binary Tree(反转二叉树 使用二级指针交换两个指针的地址)
来源:互联网 发布:四知文言文答案 编辑:程序博客网 时间:2024/06/03 21:04
1. Problem Description
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.
2. My solution(0ms)
反转二叉树,题目中给出的TreeNode类实现:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
思路很简单,递归交换左右子树,关键在于,如何交换两个指针的地址。
如果要交换两个指针的值,需要使用二级指针。
void swapp(TreeNode** t1,TreeNode** t2) { TreeNode* tmp; tmp=*t1; *t1=*t2; *t2=tmp; }
My AC code:
class Solution{public: void swapp(TreeNode** t1,TreeNode** t2) { TreeNode* tmp; tmp=*t1; *t1=*t2; *t2=tmp; } void DFS(TreeNode* root) { if(root!=NULL) { DFS(root->left); DFS(root->right); swapp(&(root->left),&(root->right)); } } TreeNode* invertTree(TreeNode* root) { DFS(root); return root; }};
3. Simple solution
class Solution{public: void DFS(TreeNode* root) { if(root!=NULL) { DFS(root->left); DFS(root->right); swap(root->left,root->right); } } TreeNode* invertTree(TreeNode* root) { DFS(root); return root; }};
0 0
- ※ Leetcode - Tree - 226. Invert Binary Tree(反转二叉树 使用二级指针交换两个指针的地址)
- LeetCode 226. Invert Binary Tree(反转二叉树)
- leetcode-226. Invert Binary Tree 二叉树、递归,交换两个变量的值
- LeetCode 226. Invert Binary Tree 递归、指针交换 思考链表的交换
- LeetCode OJ-226. Invert Binary Tree(反转二叉搜索树)
- [LeetCode]226. Invert Binary Tree(反转二叉树)
- [LeetCode]226. Invert Binary Tree--反转二叉树
- LeetCode OJ 之 Invert Binary Tree(反转二叉树)
- Invert Binary Tree(反转二叉树)
- 反转二叉树(Invert Binary Tree)
- 226. Invert Binary Tree (交换二叉树左右子树)
- Leetcode 226 Invert Binary Tree 反转二叉树
- LeetCode--Invert Binary Tree (反转二叉树)Python
- 二叉树反转(Invert Binary Tree )
- Invert Binary Tree 二叉树反转
- leetcode 226. Invert Binary Tree(二叉树的镜像)
- 226.Invert Binary Tree(交换二叉树左右结点)
- 226. Invert Binary Tree -- 二叉树、递归、交换、栈
- Game
- zabbix3.0 微信报警
- [leetcode]231. Power of Two/326. Power of Three -- JavaScript 代码
- 浅谈攻击Web应用常见的技术手段
- Mysql数据库的安装及管理
- ※ Leetcode - Tree - 226. Invert Binary Tree(反转二叉树 使用二级指针交换两个指针的地址)
- 李开复:人工智能可能会让一半人失业
- include指令和include动作的区别
- 如何有效的使用闭包
- onTextChanged参数解释及实现EditText字数监听
- git配置
- Safari下载文件名乱码
- bjfu1014 古怪的实验
- Java Web学习(37):Listener学习(一)