【二叉树,这题太好玩了】226. Invert Binary Tree
来源:互联网 发布:北京网络口碑营销公司 编辑:程序博客网 时间:2024/06/05 02:59
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9to
4 / \ 7 2 / \ / \9 6 3 1Trivia:
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.
解答:
哈哈哈哈哈,太萌了这个题。。。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* invertTree(TreeNode* root) { if(!root) return nullptr; TreeNode* tmp; tmp=root->left; root->left=root->right; root->right=tmp; invertTree(root->left); invertTree(root->right); return root; }};上面的代码还是很有意思的。。。有返回值,但是却没有赋值。。充分利用了递归。
更优雅的解法是这样:
TreeNode* invertTree(TreeNode* root) { TreeNode* temp; if(root==NULL) return root; temp=root->left; root->left=invertTree(root->right); root->right=invertTree(temp); return root;}
另一个人的BFS,也很简单:
TreeNode* invertTree(TreeNode* root) { if(nullptr == root) return root; queue<TreeNode*> myQueue; // our queue to do BFS myQueue.push(root); // push very first item - root while(!myQueue.empty()){ // run until there are nodes in the queue TreeNode *node = myQueue.front(); // get element from queue myQueue.pop(); // remove element from queue if(node->left != nullptr){ // add left kid to the queue if it exists myQueue.push(node->left); } if(node->right != nullptr){ // add right kid myQueue.push(node->right); } // invert left and right pointers TreeNode* tmp = node->left; node->left = node->right; node->right = tmp; } return root;}
阅读全文
0 0
- 【二叉树,这题太好玩了】226. Invert Binary Tree
- 226. Invert Binary Tree 翻转二叉树
- 226. Invert Binary 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(反转二叉搜索树)
- 226.leetcode Invert Binary Tree(easy)[二叉树 递归]
- 226. Invert Binary Tree (交换二叉树左右子树)
- [LeetCode]226. Invert Binary Tree(反转二叉树)
- 226. Invert Binary Tree -- 二叉树、递归、交换、栈
- [LeetCode]226. Invert Binary Tree--反转二叉树
- 翻转二叉树(Invert Binary Tree)
- 二叉树反转(Invert Binary Tree )
- [Java]Invert Binary Tree翻转二叉树
- Invert Binary Tree(翻转二叉树)
- LintCode --invert-binary-tree(翻转二叉树)
- 第三章 将 selenium集成到scrapy中
- MyBatis 笔记(五)——动态 SQL
- MySQL中InnoDB引擎--特点
- Linux进程入门学习(七)-信号通信
- JAVASE基础(十五)
- 【二叉树,这题太好玩了】226. Invert Binary Tree
- idea rest client 文件上传
- ChatGirl 一个基于 TensorFlow Seq2Seq 模型的聊天机器人[中文文档]
- 牛客网(直通BAT面试算法班) Day1
- SVN常见问题
- Apache Hadoop 2.2.0 HDFS HA + YARN多机部署
- Java多线程调度器(ScheduledThreadPoolExecutor)
- jpa case when otherwise end 的用法
- 【USACO】数学题——Bovine Bridge Battle