力扣——翻转二叉树

翻转一棵二叉树。

示例:

输入:

     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.right == null && root.left == null)) {
            TreeNode right = root.right;
            TreeNode left = root.left;
            root.right = left;
            root.left = right;
            //翻转下一次层级,判断非空
            if (root.right != null) {
                invertTree(root.right);
            }
            //翻转下一次层级,判断非空
            if (root.left != null) {
                invertTree(root.left);
            }
        }

        return root;
    }
}

猜你喜欢

转载自www.cnblogs.com/JAYPARK/p/10352001.html