zoukankan      html  css  js  c++  java
  • [Leetcode 82] 116 Populating Next Right Pointers In Each Node

    Problem:

    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 toNULL.

    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

    Analysis:

    The problem is not that hard and a little tricky. Remember when we are at level i, we can process the link relation of level i+1. And connect the left and right children of a node is easy. But how to connect the right node and left node of two different parent nodes? We can use the root->next->left to get the left node and thus finish the connecting process.

    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         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (root == NULL || (root->left == NULL && root->right == NULL))
    15             return ;
    16             
    17         root->left->next = root->right;
    18         if (root->next != NULL)
    19             root->right->next = root->next->left;
    20             
    21         connect(root->left);
    22         connect(root->right);
    23     }
    24 };
    View Code
  • 相关阅读:
    C#事件和委托的区别
    已知有个rand7()的函数,返回1到7随机自然数,让利用这个rand7()构造rand10()随机1~10
    如何搭建github+hexo博客-转
    ngRouter和ui-router区别
    JS数组追加数组采用push.apply的坑(转)
    vue中关于computed的一点理解
    simplify the life ECMAScript 5(ES5)中bind方法简介
    github使用-知乎的某小姐的一篇文章
    Jade 模板引擎使用
    玩转Nodejs日志管理log4js(转)
  • 原文地址:https://www.cnblogs.com/freeneng/p/3209772.html
Copyright © 2011-2022 走看看