lintcode-easy-Invert Binary Tree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Invert Binary Tree相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

二叉树-------二叉链表实现

记录一个优秀的图像二值化代码

LeetCode栈 stack(共40题)

new tab是啥

thrift数据类型科普

简单的验证码解决