zoukankan      html  css  js  c++  java
  • 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;
                }
            }
        }
    }
  • 相关阅读:
    datum of data matrix
    data matrix with opensource
    wps出现“文档已被其他应用程序锁定,是否以只读模式打开”
    error MSB3073解决办法
    vc6下dll调试
    往客户机子上装dll时,报缺失mfc42d.dll
    进程通信编码和解码
    java后端选型20200729
    Git安装与使用
    Kitty基于Spring Boot、Spring Cloud、Vue.js、Element实现前后端分离的权限管理系统
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10205207.html
Copyright © 2011-2022 走看看