您的位置:首页 > 编程语言 > Java开发

[Java]Invert Binary Tree翻转二叉树

2015-08-15 22:29 597 查看
leetcode 原题链接:https://leetcode.com/problems/invert-binary-tree/

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 leetcode 二叉树