码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:populating_next_right_pointers_in_each_node题解

时间:2014-10-05 21:52:19      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   bfs   结构   

一、     题目

对于结构体:struct TreeLinkNode {

             TreeLinkNode *left;

             TreeLinkNode *right;

             TreeLinkNode *next;

           }

填充所有的结点如果存在右侧的节点,则指上(next)右节点;如果没有右侧的节点,那么就指上NULL,最初都指上NULL。

 提示:只能使用给定的空间,并且你可以认为给定的二叉树是一个完美的二叉树。

例如:

         1

       / \

      2   3

     / \   \

    4  5    7

处理后:

         1 -> NULL

       / \

      2 -> 3 -> NULL

     / \   \

    4-> 5 -> 7 -> NULL

二、     分析

1、         空节点就直接返回

2、         左节点非空则连接右节点

3、         子节点连接兄弟节点的子节点,则root.right.next = root.next.left;

 

 

/**
 * Definition for binary tree with next pointer->
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root==NULL) return;
        if(root->left!=NULL) root->left->next=root->right;
        if(root->right!=NULL&&root->next!=NULL)
        	root->right->next=root->next->left;
        	
        connect(root->left);
        connect(root->right);
    }
};


BFS
/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        //breadth-first traversal
        queue<TreeLinkNode *> bfsq;
        int levelCnt=0;
        int level2=0;
        
        if(root==NULL) return;
        bfsq.push(root);
        levelCnt++;
        TreeLinkNode *prevList=NULL;
        TreeLinkNode *topS=NULL;
        
        while(!bfsq.empty()) 
        {
            topS=bfsq.front();
            bfsq.pop();
            levelCnt--;
        
            if(topS->left!=NULL && topS->right!=NULL)
            {   
                bfsq.push(topS->left);
                level2++;
                bfsq.push(topS->right);
                level2++;
            }
            
            if(prevList!=NULL)
                prevList->next=topS;
            prevList=topS;
            
            if(levelCnt==0)
            {
                levelCnt=level2;
                level2=0;
                prevList=NULL;
            }
            
        }
    }
};

 

 

Leetcode:populating_next_right_pointers_in_each_node题解

标签:leetcode   二叉树   bfs   结构   

原文地址:http://blog.csdn.net/zzucsliang/article/details/39805057

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!