• 116. Populating Next Right Pointers in Each Node


    一、题目

      1、审题

      2、分析

        给出一个完全二叉树,添加二叉树的 next 指针指向。

    二、解答

      1、思路: 

        方法一、

          采用队列进行层次遍历,遍历时添加 next 指针。

        public void connect(TreeLinkNode root) {
        
            if(root == null)
                return;
            Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
            queue.add(root);
            TreeLinkNode node;
            
            while(!queue.isEmpty()) {
                
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    node = queue.poll();
                    if(i < size - 1)
                        node.next = queue.peek();
                    if(node.left != null) {
                        queue.add(node.left);
                    }
                    if(node.right != null) {
                        queue.add(node.right);
                    }
                        
                }
            }
        }

      

      方法二、

        利用两个指针进行层次遍历,添加 next 指针

        public void connect(TreeLinkNode root) {
            if(root == null)
                return;
            TreeLinkNode pre = root;
            TreeLinkNode cur;
            while(pre.left != null) {
                cur = pre;
                while(cur != null) {
                    cur.left.next = cur.right;
                    if(cur.next != null)
                        cur.right.next = cur.next.left;
                    cur = cur.next;
                }
                pre = pre.left;
            }
        }

      

      方法三、

        利用递归实现每一层的 next 指针。

        public void connect(TreeLinkNode root) {
            if(root == null)
                return;
            
            if(root.left != null) {
                root.left.next = root.right;
                if(root.next != null)
                    root.right.next = root.next.left;
            }
            connect(root.left);
            connect(root.right);
        }
  • 相关阅读:
    HTML 常见标签part1
    HTML 初始
    jenkins远程执行脚本不退出
    jenkins 持续集成工具安装
    jenkins 杀掉衍生进程解决办法
    日志分割工具-crononlog
    可视化库 pygal 生成png中文乱码
    可视化库 pygal 无法保存成本地文件
    一个很好用的ORM库--peewee
    3 种进度条 -- 记录
  • 原文地址:https://www.cnblogs.com/skillking/p/9745232.html
Copyright © 2020-2023  润新知