Invert Binary Tree 颠倒二叉树

来源:互联网 发布:淘宝联盟登陆不上去 编辑:程序博客网 时间:2024/06/10 08:55

Invert a binary tree.

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


颠倒二叉树即对树做镜像了。

核心思想是:

1. 左右子树互换。

2. 左右子树本身也要做镜像。

递归求解


代码:

public class InvertBinaryTree {    public TreeNode invertTree(TreeNode root) {        if (root == null) {            return root;        }        TreeNode temp = invertTree(root.left);        root.left = invertTree(root.right);        root.right = temp;        return root;    }}



1 0
原创粉丝点击