zoukankan      html  css  js  c++  java
  • LeetCode OJ: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

    这题首先想到的当然是用bfs来做,但是题目只允许使用常数量的额外空间,用queue肯定是无法实现的,那么可以采取先序遍历的方式,由于是完全二叉树,所以有左孩子那么就一定也有右孩子了,所以递归的时候注意这点就可以了。下面是代码:

     1 class Solution {
     2 public:
     3     void connect(TreeLinkNode *root) {
     4         preorderTranversal(root);
     5     }   
     6 
     7     void preorderTranversal(TreeLinkNode *root)
     8     {
     9         if(!root || !root->left) return;
    10         root->left->next = root->right;
    11         if(root->next)
    12             root->right->next = root->next->left;//这一步的连接应该注意一下
    13         preorderTranversal(root->left);
    14         preorderTranversal(root->right);
    15     }
    16 };

     当然这题也可以使用非递归的方法来实现,非递归方法代码如下所示:

     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 == NULL) return ;
    13         while(root->left){
    14             TreeLinkNode * tmpRoot = root;
    15                 tmpRoot->left->next = tmpRoot->right;
    16             while(tmpRoot->next){
    17                 tmpRoot->right->next = tmpRoot->next->left;
    18                 tmpRoot = tmpRoot->next;
    19                 if(tmpRoot->left)
    20                     tmpRoot->left->next = tmpRoot->right;
    21             }
    22             root = root->left;
    23         }
    24     }
    25 };
  • 相关阅读:
    [置顶] Extjs4 异步刷新书的情况下 保持树的展开状态
    控制系统中常用的名词术语
    开环控制系统与闭环控制系统
    反馈控制
    Tensorflow把label转化成one_hot格式
    Tensorflow——tf.nn.max_pool池化操作
    Tensorflow——tf.nn.conv2d卷积操作
    Tensoflow简单神经网络实现非线性拟合
    Tensorflow 中的 placeholder
    Tensorflow 中的constant、Session、placeholde和 Variable简介
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4914246.html
Copyright © 2011-2022 走看看