zoukankan      html  css  js  c++  java
  • leetcode-116. 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

    思路:起初觉得是个很难的题,但是后来发现了Note里面的限制(给定二叉树是完全二叉树),所以简单好多,只需要逐层处理即可。

    Accepted Code:
     1 /**
     2  * Definition for binary tree with next pointer.
     3  * struct TreeLinkNode {
     4  *  int val;
     5  *  TreeLinkNode *left, *right, *next;
     6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void connect(TreeLinkNode *root) {
    12         if(root==nullptr)
    13         return;
    14         TreeLinkNode* pre=root;
    15         TreeLinkNode* cur=nullptr;
    16         while(pre->left)
    17         {
    18             cur=pre;
    19             while(cur)
    20             {
    21                 cur->left->next=cur->right;
    22                 if(cur->next)
    23                 {
    24                     cur->right->next=cur->next->left;
    25                     cur=cur->next;
    26                 }else
    27                 break;
    28             }
    29             pre=pre->left;
    30         }
    31     }
    32 };
  • 相关阅读:
    缩放图片
    Volley下载图片存放在data/data下 networkImageView lrucache
    类实现Parcelable接口在Intent中传递
    基本控件设置边角图片 drawableleft
    屏幕全屏之类的问题
    关于点击按钮分享
    万能适配器的一些问题
    自定义控件高级
    Fragment 生命周期 全局变量的声明位置
    GridView
  • 原文地址:https://www.cnblogs.com/hongyang/p/6464194.html
Copyright © 2011-2022 走看看