非递归法解题思路

二叉树的镜像

http://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011

看到题解里都是简单的递归方法,由于面试中面试官多会问非递归的方法,这里提供非递归的代码。供参考。

思路:镜像就是将“根”节点的左右两个“子”节点互换,类似于数组的元素交换(运用临时节点temp)
利用二叉树的广度优先搜索即可

public void Mirror(TreeNode root) {
        if(root == null) return;
        Queue<TreeNode> nodes = new LinkedList<>();
        TreeNode curr, temp;
        nodes.offer(root);
        while(!nodes.isEmpty()){
            int len = nodes.size();
            for(int i = 0; i < len; i++){
                curr = nodes.poll();
                temp = curr.left;
                curr.left = curr.right;
                curr.right = temp;
                if(curr.left != null) nodes.offer(curr.left);
                if(curr.right != null) nodes.offer(curr.right);
            }
        }
    }
全部评论
for语句那一行貌似可以删掉
2 回复 分享
发布于 2020-01-16 10:10
这个for循环没看太懂,好像没必要
1 回复 分享
发布于 2020-05-08 17:18
这个for循环不需要
1 回复 分享
发布于 2020-08-16 18:51
为啥我有导包问题啊
点赞 回复 分享
发布于 2020-01-31 23:00
2333和我的想法一模一样,代码也几乎一样
点赞 回复 分享
发布于 2020-03-21 13:35
牛牛牛
点赞 回复 分享
发布于 2020-07-10 20:23
Queue飘红是咋回事
点赞 回复 分享
发布于 2020-10-12 15:53

相关推荐

许愿ssp的咸鱼很不想泡池子:import python as pyhton
点赞 评论 收藏
分享
新记话事人:你就和她说去抖音了
点赞 评论 收藏
分享
评论
19
4
分享

创作者周榜

更多
牛客网
牛客企业服务