[Java]Invert Binary Tree翻转二叉树
2015-08-15 22:29
597 查看
leetcode 原题链接:https://leetcode.com/problems/invert-binary-tree/
Invert a binary tree.
to
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.
简要分析:本题其实很简单,要求就是将每一个节点的左右子树对调位置。需要注意的就是,我发现,leetcode给的函数模型是需要返回值的,因此我猜测这道题中是不能改变原来的二叉树的。
因此在遍历原二叉树的时候,需要new出新节点,并进行左右对调。
具体实现代码:
<span style="font-size:14px;">public TreeNode invertTree(TreeNode root)
{
if (root == null)
return null;
TreeNode nroot = new TreeNode(root.val);
if (root.left != null)
{
nroot.right = new TreeNode(root.left.val);
invertTree(root.left, nroot.right);
}
if (root.right != null)
{
nroot.left = new TreeNode(root.right.val);
invertTree(root.right, nroot.left);
}
return nroot;
}
private void invertTree(TreeNode root, TreeNode nroot)
{
// TODO Auto-generated method stub
if (root.left != null)
{
nroot.right = new TreeNode(root.left.val);
invertTree(root.left, nroot.right);
}
if (root.right != null)
{
nroot.left = new TreeNode(root.right.val);
invertTree(root.right, nroot.left);
}
return;
}</span>
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.
简要分析:本题其实很简单,要求就是将每一个节点的左右子树对调位置。需要注意的就是,我发现,leetcode给的函数模型是需要返回值的,因此我猜测这道题中是不能改变原来的二叉树的。
因此在遍历原二叉树的时候,需要new出新节点,并进行左右对调。
具体实现代码:
<span style="font-size:14px;">public TreeNode invertTree(TreeNode root)
{
if (root == null)
return null;
TreeNode nroot = new TreeNode(root.val);
if (root.left != null)
{
nroot.right = new TreeNode(root.left.val);
invertTree(root.left, nroot.right);
}
if (root.right != null)
{
nroot.left = new TreeNode(root.right.val);
invertTree(root.right, nroot.left);
}
return nroot;
}
private void invertTree(TreeNode root, TreeNode nroot)
{
// TODO Auto-generated method stub
if (root.left != null)
{
nroot.right = new TreeNode(root.left.val);
invertTree(root.left, nroot.right);
}
if (root.right != null)
{
nroot.left = new TreeNode(root.right.val);
invertTree(root.right, nroot.left);
}
return;
}</span>
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统