Leetcode 226. 翻转二叉树

题目链接

https://leetcode-cn.com/problems/invert-binary-tree/description/

题目描述

翻转一颗二叉树

示例

输入:

     4
   /   
  2     7
 /    / 
1   3 6   9

输出:

     4
   /   
  7     2
 /    / 
9   6 3   1

题解

使用递归的方式来求解。需要注意的是,在翻转的过程中,注意保存树节点的一个副本,不然在后面的翻转中会存在重复的结果,使用了已经翻转的子树。

代码

/**
 * 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; }
        if (root.left == null && root.right == null) { return root; }
        TreeNode tmp = null;
        if (root.left != null) { 
            tmp = root.left; 
            root.left = invertTree(root.right);
            root.right = invertTree(tmp);
        }
        else {
            tmp = root.right;
            root.right = invertTree(root.left);
            root.left = invertTree(tmp);
        }
        return root;
    }
}
原文地址:https://www.cnblogs.com/xiagnming/p/9540414.html