leetcode刷题--翻转二叉树

题目描述:
Invert a binary tree.

Example:

Input:

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

Output:

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

算法思想:
对于二叉树的算法基本都往递归方向考虑,那么这道题的根本是

  1. 翻转左右子树
  2. 交换左右子树
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null || (root.left == null && root.right == null))
        {
            return root;
        }
        TreeNode temp = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(temp);
        return root;
    }
   
}

你可能感兴趣的:(leetcode)