您的位置:首页 > 其它

LeetCode -- Invert Binary Tree

2015-09-26 23:13 344 查看
Question:

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.


Analysis:

问题描述:给出一个二叉树,然后将它的左右子树置换。

思路:这种题目首先应该反射到递归。用递归有两个条件:return 语句的书写和递归语句的书写。在这道题目中,只要一个节点有任何左节点或者右节点,则应该将他们置换。因此只要非空就置换



Answer:

/**
* 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 t = root.left;
root.left = root.right;
root.right = t;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: