• 117. Populating Next Right Pointers in Each Node II


    Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
    

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

    Initially, all next pointers are set to NULL.

    Note:

    • You may only use constant extra space.
    • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

    Example:

    Given the following binary tree,

         1
       /  
      2    3
     /     
    4   5    7
    

    After calling your function, the tree should look like:

         1 -> NULL
       /  
      2 -> 3 -> NULL
     /     
    4-> 5 -> 7 -> NULL

    这题和 116. Populating Next Right Pointers in Each Node - Medium 不同的是本题的树不是perfect tree,每个节点并不是都有左右子节点

    用dummy指向每层的首节点的前一个节点,用cur遍历这一层,然后连下一层的next。从root开始,如果左子节点存在,cur的next连上左子节点,然后cur指向其next指针;如果右子节点存在,cur的next连右子节点,然后cur指向其next指针。此时移动root,指向其next指针,如果此时root为null,说明当前层已经遍历完,重置cur为dummy结点,root此时为dummy.next,即下一层的首节点,然后dummy的next指针清空

     time: O(n), space: O(1)

    /**
     * Definition for binary tree with next pointer.
     * public class TreeLinkNode {
     *     int val;
     *     TreeLinkNode left, right, next;
     *     TreeLinkNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root == null) {
                return;
            }
            TreeLinkNode dummy = new TreeLinkNode(0);
            TreeLinkNode cur = dummy;
            
            while(root != null) {
                if(root.left != null) {
                    cur.next = root.left;
                    cur = cur.next;
                }
                if(root.right != null) {
                    cur.next = root.right;
                    cur = cur.next;
                }
                root = root.next;
                if(root == null) {
                    cur = dummy;
                    root = dummy.next;
                    dummy.next = null;
                }
            }
        }
    }
  • 相关阅读:
    SQL注入绕过——主要是magic_quotes_gpc, is_int(只能跑路,无注入点),以及关键字绕过,WAF绕过
    小葵多功能转换工具——编解码绕过,TODO
    load_file() 常用敏感信息
    crontab 结合 thinkphp3.2
    Docker 小型电脑
    Linux 查找大目录
    phpmyadmin 连接远程数据库
    git 变更 地址
    showdoc可以导出
    showdoc搭建
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10205207.html
Copyright © 2020-2023  润新知