226. Invert Binary Tree

Question

Invert a binary tree.

Example:

Input:

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

Output:

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

Thinking:

  • Method:递归
    • 通过递归,不断反转当前结点的两个子结点。
    • 当遇到空节点时退出。
/**
 * 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 root;
        TreeNode temp = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(temp);
        return root;
    }
}

二刷

  1. Still use recursion to solve this problem.
  2. Same as swap two variables, use a temp node to save and swap the two values.
    /**
     * 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){
             TreeNode temp = null;
             temp = invertTree(root.right);
             root.right = invertTree(root.left);
             root.left = temp;
         }
         return root;
     }
    }