首页 > 代码库 > [LeetCode] 226. Invert Binary Tree JAVA

[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

题意及分析:给出一棵二叉树,对每个节点交换左右子树。对于一个需要交换的节点有三种情况:(1)有左子树,无右子树;(2)有右子树,无左子树;(3)左右子树都有;对着三种情况分别交换左右子树,然后继续对子树递归即可得到结果。

代码:

/**
 * 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) {
        if(root==null) return null;
        exchange(root);
        return root;
    }

    public void exchange(TreeNode node){
        if(node.left==null&&node.right==null)
            return;
        else{
            if(node.left==null&&node.right!=null){
                node.left=node.right;
                node.right=null;
                exchange(node.left);
                return;
            }else if(node.right==null&&node.left!=null){
                node.right=node.left;
                node.left=null;
                exchange(node.right);
            }else{
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                exchange(node.left);
                exchange(node.right);
            }
        }
    }
}

 

[LeetCode] 226. Invert Binary Tree JAVA