题目描述:给一个二叉树,反转它
Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
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 f*** off.
思路:
递归,从根节点出发,反转当前节点的左子树和右子树
边界条件:当前节点没有子节点就返回,否则继续递归
递归前进段:当前节点有子节点
递归返回段:当前节点没有子节点
代码实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode invertTree(TreeNode root) { // 思路 // 递归来做,从根节点出发,将其左子树和右子树位置进行调换 // 边界条件,当前节点没有子节点了,那么就返回,否则继续递归 // 递归前进段:当前节点有子节点 // 递归返回段:当前节点没有子节点 if(root == null) return null; TreeNode tmp = root.left; root.left = invertTree(root.right); root.right = invertTree(tmp); return root; } }