leetcode:Inver Binary Tree

1、

Invert a binary tree.

  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

2、
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        //是否停止
        if (root == null) {
            return;
        }
        //同棵树的左右值互相对换
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        //左右再次遍历,逐一遍历下去
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);
 
    }
}

 

 
posted @ 2016-03-18 16:28  自朗活  阅读(107)  评论(0)    收藏  举报