zoukankan      html  css  js  c++  java
  • [LeetCode] Populating Next Right Pointers in Each Node

    
    

    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.
    • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

    For example,
    Given the following perfect binary tree,

             1
           /  
          2    3
         /   / 
        4  5  6  7
    

    After calling your function, the tree should look like:

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

     解题思路:

    按层遍历一遍所有结点即可,每一次从左到右枚举一次当前层的节点(这一层的节点已经连上),如果下一层为空,则退出,否则顺序地将下一层连起来。

    /**
     * Definition for binary tree with next pointer.
     * struct TreeLinkNode {
     *  int val;
     *  TreeLinkNode *left, *right, *next;
     *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
        if(root == NULL)
            return;
            
        TreeLinkNode *head = root, *last = root, *tmp_last = root;//store the horizontal list
        root -> next = NULL;
        
        //if head -> left == NULL, then this is the leaf level, end
        while(head -> left != NULL)
        {
            //list the head level node
            last = head -> left;//last stores the next level, which is what we want to connect
            last -> next = head -> right;//connect the right to the left
            last = head -> right;//last node switch to the right node of the head
            tmp_last = head;//head level last node
            while(tmp_last -> next != NULL)
            {
                tmp_last = tmp_last -> next;
                last -> next = tmp_last -> left;
                (tmp_last -> left) -> next = tmp_last -> right;
                last = tmp_last -> right;
            }
            
            last -> next = NULL;
            head = head -> left;
        } 
        }
    };
  • 相关阅读:
    最近积累的JS 东西,分享一下
    C#定时任务框架Quartz.NET
    如何成为微软社区MVP以及年终总结
    git 基于某个分支创建分支
    iframe跨域-Js通信的一种方式
    tcp连接建立断开过程及状态变化
    MySQL-InnoDB的事务隔离与锁
    MySQL索引原理总结
    php gd实现简单图片验证码与图片背景文字水印
    php 取post数据的三种方式
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415988.html
Copyright © 2011-2022 走看看