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;
                }
            }
        }
    }
  • 相关阅读:
    【Python】自己写日志功能
    shell 笔记
    python 字典,字典嵌套,字典遍历
    python基础 循环,列表,切片,列表增删改查
    Dva_react使用问题总结
    ts_react_test报错解决方法
    如何写好项目规划和方案设计文档 (转)
    script标签引入react环境三个必须cdn文件
    react点击事件对象( react封装过后事件对象 )
    react简书笔记一 环境, git 和 项目 关联
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10205207.html
Copyright © 2011-2022 走看看