码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Invert Binary Tree

时间:2016-02-26 06:56:51      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

Invert a binary tree.

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

Do it in recursion is acceptable, can you do it without recursion?

 

1. 递归

/**
 * 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) {
        // write your code here
        if(root == null)
            return;
        
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);
        
        TreeNode temp = root.right;
        
        root.right = root.left;
        root.left = temp;
        
        return;
    }
}

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) {
        // write your code here
        if(root == null)
            return;
        
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        
        while(!queue.isEmpty()){
            TreeNode p = queue.poll();
            
            if(p.left != null)
                queue.offer(p.left);
            if(p.right != null)
                queue.offer(p.right);
            
            TreeNode temp = p.right;
            p.right = p.left;
            p.left = temp;
        }
        
        return;
    }
}

 

lintcode-easy-Invert Binary Tree

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5218919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!