程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

編輯:C++入門知識

題目:


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
代碼如下:

void build(TreeLinkNode *root)
    {
        if(root->left!=NULL)
        {
            root->left->next=root->right;
            if(root->next!=NULL)
            {
                root->right->next=root->next->left;
            }
            else
            {
                root->right->next=NULL;
            }
            build(root->left);
            build(root->right);
        }
    }
    void connect(TreeLinkNode *root) {
        if(root==NULL)return;
        root->next=NULL;
        build(root);
        return; 
    }


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved