交换左右子树 Invert Binary Tree

题目:node

Invert a binary tree.this

     4
   /   \
  2     7
 / \   / \
1   3 6   9

tospa

     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.

解决:get

① 直接递归交换左右子树。it

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution { //0ms
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
io

② 在discuss部分看到了使用dfs实现交换,须要建立一个新的tree用于保存交换后的树。class

public class Solution { //0ms
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        TreeNode invertedRoot = new TreeNode(0);
        getInvertTree(root, invertedRoot);
        return invertedRoot;
    }
    public void getInvertTree(TreeNode root, TreeNode invertedRoot){
        if(root == null) return;  
        invertedRoot.val = root.val;

        if(root.left != null){
            invertedRoot.right = new TreeNode(0);
            getInvertTree(root.left, invertedRoot.right);
        }
        if(root.right != null){
            invertedRoot.left = new TreeNode(0);
            getInvertTree(root.right, invertedRoot.left);
        }
    }
}di

相关文章
相关标签/搜索