• 117. Populating Next Right Pointers in Each Node II(js)


    117. Populating Next Right Pointers in Each Node II

    Given a binary tree

    struct Node {
      int val;
      Node *left;
      Node *right;
      Node *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.

    Example:

    Input: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
    
    Output: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}
    
    Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B.
    题意:当树不是完全二叉树时,给每个节点加一个next指针指向右方的节点
    代码如下:
    /**
     * Definition for binary tree with next pointer.
     * function TreeLinkNode(val) {
     *     this.val = val;
     *     this.left = this.right = this.next = null;
     * }
     */
    
    /**
     * @param {TreeLinkNode} root
     * @return {void} Do not return anything, modify tree in-place instead.
     */
    var connect = function(root) {
        if(!root)
            return null;
        let head = root;
        let dummy = new Node();
        while(root) {
            let currChild = dummy;
            while(root) {
                if(root.left) {
                    currChild.next = root.left;
                    currChild = currChild.next;
                }
                if(root.right) {
                    currChild.next = root.right;
                    currChild = currChild.next;
                }
                root = root.next;
            }
            root = dummy.next;
            dummy.next = null;
        }
        return head;
    };
  • 相关阅读:
    源码0603-08-掌握-NSURLSession-上传
    源码0603-05-掌握-大文件下载
    源码0603-03-掌握-NSURLSession
    源码0603-01-了解-大文件下载(NSOutputStream)
    源码0602-10-掌握-文件上传11-了解-获得文件的MIMEType
    源码0602-08-掌握-解压缩
    源码0602-06-掌握-小文件下载-大文件下载
    用JS实现的控制页面前进、后退、停止、刷新以及加入收藏等功能
    java一路走来
    CKEditor3.5.3 JAVA下使用
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10777759.html
Copyright © 2020-2023  润新知