翻转一棵二叉树(非递归版本)

翻转一棵二叉树(非递归版本)

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;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
        }
    }
}

解题思路:
通过队列将每个节点的左右子节点翻转

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 4,510评论 1 31
  • 什么是二叉树? 引用自百度百科:在计算机科学中,二叉树是每个节点最多有两个子树的树结构。通常子树被称作“左子树”(...
    AnICoo1阅读 1,402评论 0 1
  • 前言 2. 实现 Singleton 3. 数组中重复的数字 4. 二维数组中的查找 5. 替换空格 6. 从尾到...
    Observer_____阅读 3,022评论 0 1
  • 本文转自 http://www.cnblogs.com/manji/p/4903990.html二叉树-****你...
    doublej_yjj阅读 696评论 0 8
  • 最近在网上, 看到了马云的创业故事! 这部阿里的纪录片, 让我看到了一个人对价值观的永不放弃! 值得你花一个小时看...
    ellweniing阅读 245评论 0 0