Leetcode __226. 翻转二叉树

问题描述

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
输出:

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

思路

第一个想法就是递归(感觉对于二叉树而言,递归是最好做的)

  1. 数为空的时候直接返回null
  2. 不为空的时候,就好像一个交换位置的操作,加一个中间变量接一下,交换值,交换的值要递归操作

实现

/**
 * 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;
        } else if (root.right == null && root.left == null) {
            return root;
        } else {
            TreeNode tem = root.right;
            root.right = invertTree(root.left);
            root.left = invertTree(tem);
        }
        return root;
    }
}

Leetcode __226. 翻转二叉树_第1张图片

遇到的问题

  • 反转二叉树,反转的是值还是节点,如果单反转值的话,对应的位置没有节点,赋值的时候会报错,所以反转的是节点,节点反转过来,自然值就对应过来
  • 交换位置的时候,要注意中间变量留的是谁,不要对应反了,第一次被赋值的,即留下的中间变量。

你可能感兴趣的:(LeetCode,每日一结)