zoukankan      html  css  js  c++  java
  • 在每个节点填充向右的指针 Populating Next Right Pointers in Each Node

    2018-08-09 16:01:40

    一、Populating Next Right Pointers in Each Node

    问题描述:

    问题求解:

    由于是满二叉树,所以很好填充。

        public void connect(TreeLinkNode root) {
            if (root != 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);
            }
        }
    

    二、Populating Next Right Pointers in Each Node II

    问题描述:

    问题求解:

    本题中因为不再是满二叉树,因此不能简单的使用先序遍历进行求解,因为先序遍历是有先后顺序的,因此单纯采用先序遍历会出现丢失的现象。因此只能使用按行求解。

        public void connect(TreeLinkNode root) {
            if (root == null) return;
            TreeLinkNode dummy = new TreeLinkNode(-1);
            for (TreeLinkNode cur = root, pre = dummy; cur != null; cur = cur.next) {
                if (cur.left != null) {
                    pre.next = cur.left;
                    pre = pre.next;
                }
                if (cur.right != null) {
                    pre.next = cur.right;
                    pre = pre.next;
                }
            }
            connect(dummy.next);
        }
    
  • 相关阅读:
    mabatis配置文件yml配置打印sql
    java使用validator检验bean
    vue项目 老是报错 气的我就不行
    注入为空
    软件测试基础
    单元测试实战
    软件测试基础
    For循环案例---九九乘法表
    软件测试基础
    软件测试基础
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9450905.html
Copyright © 2011-2022 走看看