leetcode 226. Invert Binary Tree 反转二叉树 + DFS深度优先搜索
来源:互联网 发布:淘宝ifashion质量好么 编辑:程序博客网 时间:2024/06/05 07:26
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.
这个就是最经典的反转二叉树的实现。
直接递归即可。
代码如下:
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;/*class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}*//* * 这就是传说中牛逼哄哄的反转二叉树的问题 * 递归解决即可 * 假如是非递归解法,要注意这可能表示满二叉树 * */public class Solution { public TreeNode invertTree(TreeNode root) { if(root==null) return root; invert(root); return root; } public void invert(TreeNode root) { if(root!=null) { TreeNode tmp=root.left; root.left=root.right; root.right=tmp; invert(root.left); invert(root.right); }else return; }}
下面是C++的做法,就是一个简单的DFS深度优先遍历的简单应用
代码如下:
#include <iostream>#include <algorithm>#include <vector>#include <set>#include <map>using namespace std;/*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 == NULL) return root; else { TreeNode* tmp = root->left; root->left = root->right; root->right = tmp; invertTree(root->left); invertTree(root->right); return root; } }};
阅读全文
0 0
- leetcode 226. Invert Binary Tree 反转二叉树 + DFS深度优先搜索
- LeetCode OJ-226. Invert Binary Tree(反转二叉搜索树)
- LeetCode 226. Invert Binary Tree(反转二叉树)
- [LeetCode]226. Invert Binary Tree(反转二叉树)
- [LeetCode]226. Invert Binary Tree--反转二叉树
- leetcode 669. Trim a Binary Search Tree 修建二叉搜索树BST + 深度优先遍历DFS
- LeetCode OJ 之 Invert Binary Tree(反转二叉树)
- Leetcode 226 Invert Binary Tree 反转二叉树
- LeetCode--Invert Binary Tree (反转二叉树)Python
- 二叉树反转(Invert Binary Tree )
- Invert Binary Tree 二叉树反转
- Invert Binary Tree(反转二叉树)
- 反转二叉树(Invert Binary Tree)
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- ※ Leetcode - Tree - 226. Invert Binary Tree(反转二叉树 使用二级指针交换两个指针的地址)
- [LeetCode][二叉树]Invert Binary Tree
- LeetCode Invert Binary Tree 翻转二叉树
- 【LeetCode】Invert Binary Tree 翻转二叉树
- android studio中如何设置注释模板---项目开发规范
- 关于double计算精度丢失解决办法
- Axure8.0汉化包+注册码
- C#设计模式—单例模式
- win10JAVA环境变量的配置及解决输入javac提示不是内部命令
- leetcode 226. Invert Binary Tree 反转二叉树 + DFS深度优先搜索
- Apache Spark 2.2.0 中文文档
- intellij idea实用插件
- Java过滤器与SpringMVC拦截器之间的关系与区别
- YOLO9000好棒好快好强壮 阅读笔记
- LeetCode——Container With Most Water
- Android Studio 使用魅族手机调试时,不显示 Log 的解决方法
- 工作随笔---WiFi开发(5)---WIFIWpsConnect类
- Python 字典基础回顾