LeetCode 226 -Invert Binary Tree ( JAVA )

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     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; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        TreeNode inv = new TreeNode(0);
        if(root != null){
            TreeNode T = new TreeNode(0);
            T = root.left ;
            root.left = root.right;
            root.right = T;
            invertTree(root.left);
            invertTree(root.right);
        }
        return root;
    }
}


LeetCode 226 -Invert Binary Tree ( JAVA )_第1张图片


总结:从题目可以看出需要把二叉树的每一个左右孩子节点做一次调换,因为每次操作都是一样重复的,所以首先想到了,递归调用(效率低),每次左右调换,最后return root;

你可能感兴趣的:(LeetCode 226 -Invert Binary Tree ( JAVA ))