• leetcode——116.填充每一个节点的下一个右侧节点指针


    虽然做出来了,但是好像效果并不是很好。。

    public Node connect(Node root) {
            if(root == null){
                return null;
            }
            //构建一个队列
            Queue<Node> queue = new ArrayDeque<>();
            queue.add(root);
            int n = 1;
            Node node = null;
            int i = 0;
            while(!queue.isEmpty()){
                while(i<Math.pow(2,n)-1){
                    node = queue.poll();
                    if(node != null) {
                        if(i != Math.pow(2,n)-2) {
                            node.next = queue.peek();
                        }else{
                            node.next = null;
                        }
                        if(node.left != null) {
                            queue.add(node.left);
                        }
                        if(node.right != null) {
                            queue.add(node.right);
                        }
                    }
                    i++;
                }
                n++;
            }
            return root;
        }

     用队列以及两层循环嵌套完成。


    别人的例子:

    public Node connect(Node root) {
            if(root == null) return null;
    
            if(root.left != null){
                root.left.next = root.right;
            }
            if(root.right != null && root.next != null){
                root.right.next = root.next.left;
            }
    
            connect(root.left);
            connect(root.right);
            return root;
        }

    多巧妙啊这个!!!

    ——2020.7.3

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    APPlication,Session和Cookie的区别
    C# 中的Request对象的应用
    从字符串里提取一个列表(数组)
    UDP:用户数据报协议
    反射
    网络编程
    多线程
    final,finally和finalize的区别
    集合
    StringBuffer
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13228807.html
Copyright © 2020-2023  润新知