Leetcode226 Invert Binary Tree
来源:互联网 发布:二叉树求节点双亲算法 编辑:程序博客网 时间:2024/05/21 22:44
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.
public class Solution226 { public void layerTraverse(TreeNode root) { Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { TreeNode tmp = queue.poll(); System.out.print(tmp.val + " , "); if(tmp.left != null) { queue.add(tmp.left); } if(tmp.right != null) { queue.add(tmp.right); } } } public TreeNode invertTree(TreeNode root) { if(root == null) return root; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { TreeNode tmp = queue.poll(); TreeNode left = tmp.left, right= tmp.right; tmp.left = right; tmp.right = left; if(left!=null) { queue.add(left); } if(right != null) { queue.add(right); } } return root; } public static void main(String[] args) { TreeNode root = new TreeNode(4); root.left = new TreeNode(2); root.right = new TreeNode(7); root.left.left = new TreeNode(1); root.left.right = new TreeNode(3); root.right.left = new TreeNode(6); root.right.right = new TreeNode(9); Solution226 ans = new Solution226(); ans.layerTraverse(root); root = ans.invertTree(root); System.out.println(); ans.layerTraverse(root); }}
0 0
- LeetCode226:Invert Binary Tree
- Leetcode226 Invert Binary Tree
- leetcode226 Invert Binary Tree
- LeetCode226. Invert Binary Tree
- leetcode226: Invert Binary Tree
- leetcode226. Invert Binary Tree
- leetcode226. Invert Binary Tree
- python--leetcode226. Invert Binary Tree
- LeetCode226——Invert Binary Tree
- 剑指offer 面试题19:二叉树的镜像(leetcode226. Invert Binary Tree) 题解
- [leetcode] Invert Binary Tree
- [LeetCode]Invert Binary Tree
- Invert Binary Tree
- leetcode:Invert Binary Tree
- Invert Binary Tree
- LeetCode Invert Binary Tree
- 226Invert Binary Tree
- LeetCode | Invert Binary Tree
- Windows批处理学习之目录操作类命令
- 图像滤镜艺术---(Sketch Filter)素描滤镜
- 一个c语言写的文件系统
- Object转为String的几种形式
- 图像滤镜艺术---水彩画滤镜
- Leetcode226 Invert Binary Tree
- OK6410 解决Qt移植后触摸屏不能使用、鼠标无法移动问题
- 2015年9月12日模拟赛总结
- 一种实现单元测试的方法及装置
- [源码]使用startService和boundService两种方法实现播放歌曲DEMO
- Android Support v4、v7、v13 介绍
- 计算器(栈实现)
- mac os x下python安装MySQLdb模块
- POJ 2251 Dungeon Master