zoukankan      html  css  js  c++  java
  • 【题解】【BT】【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

    思路:

    这题看似Binary Tree Level Order Traversal,实则因为满二叉树的设定,相比要简单太多,提前计算好每层的节点数就OK

    代码:

     1 void connect(TreeLinkNode *root) {
     2     if(root == NULL) return;//考虑自身为空
     3     queue<TreeLinkNode*> nodeQ;
     4     nodeQ.push(root);
     5     int n = 1;
     6     int i = 0;
     7     while(!nodeQ.empty()){
     8         TreeLinkNode* top = nodeQ.front();
     9         nodeQ.pop();
    10         if(++i != n){
    11             top->next = nodeQ.front();
    12         }else{
    13             n *= 2;
    14             i = 0;
    15         }
    16         if(top->left != NULL)//考虑左右子树为空(叶子节点)的情况
    17             nodeQ.push(top->left);
    18         if(top->right != NULL)
    19             nodeQ.push(top->right);
    20     }
    21 }
  • 相关阅读:
    在其他机器上安装mysql和hive后设置hive元数据存储为mysql
    MapReduce作业切片和Shuffle
    sns 批量清除脚本
    PHP 汉字 转换成 拼音
    PHPCMS V9 和其他应用同步
    nginx启动,重启,关闭命令
    Linux下zip unzip的用户示例 解压到指定目录
    nginx phpcms rewrite规则
    javascript 里面嵌套方法
    数制及其转换
  • 原文地址:https://www.cnblogs.com/wei-li/p/PopulatingNextRightPointersinEachNode.html
Copyright © 2011-2022 走看看