226. Invert Binary Tree
Posted wx62ea2466cca9a
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了226. 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.
/**
* Definition for a binary tree node.
* public 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 null;
TreeNode tempNode = root.left;
root.left = root.right;
root.right = tempNode;
invertTree(root.left);
invertTree(root.right);
return root;
/**
* Definition for a binary tree node.
* public 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;
TreeNode curr = new TreeNode(root.val);
curr.right = invertTree(root.left);
curr.left = invertTree(root.right);
return curr;
以上是关于226. Invert Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode226]Invert Binary Tree
leetcode 226 Invert Binary Tree