Leetcode 226. Invert Binary Tree

Invert a binary tree.

 4

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

思路:
递归的翻转每个节点的左右子树,然后交换每个节点的左右子树。

public TreeNode invertTree(TreeNode root) {
    if (root == null) {
        return root;
    }

    TreeNode left = invertTree(root.left);
    TreeNode right = invertTree(root.right);
    root.left = right;
    root.right = left;

    return root;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/d9509e76d567
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞