leetcode 原题链接:https://leetcode.com/problems/invert-binary-tree/
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.简要分析:本题其实很简单,要求就是将每一个节点的左右子树对调位置。需要注意的就是,我发现,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>