Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]

题目:
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) {
        if(root==null){
            return null;
        }
        if(root.left!=null){
            root.left=invertTree(root.left);
        }
        if(root.right!=null){
            root.right=invertTree(root.right);
        }
        TreeNode temp=root.right;
        root.right=root.left;
        root.left=temp;
        return root;
    }
}
原文地址:https://www.cnblogs.com/cxchanpin/p/7305596.html