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

Populating Next Right Pointers in Each Node I II

时间:2015-08-21 10:59:05      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

乍一看很难,理清思路后很简单的。

/**
 * 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||root->left==NULL)
            return;
        root->left->next=root->right;
        if(root->next!=NULL)
            root->right->next=root->next->left;
        connect(root->left);
        connect(root->right);
        return ;
    }
};

  II:和女朋友闹矛盾,心情不太好,就没有自己写了,直接看的网上的。

/**
 * 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(NULL == root) return;
        TreeLinkNode* start;
        TreeLinkNode* curNode;
        TreeLinkNode* nextNode;
        while(root != NULL){
            start = findStartNodeNextLev(root);
            curNode = start;
            nextNode = findNextNodeNextLev(root, start);
            while(nextNode != NULL){
                curNode -> next = nextNode;
                curNode = nextNode;
                nextNode = findNextNodeNextLev(root, curNode);
            }
            root = start;
        }
    }
private:
    TreeLinkNode* findNextNodeNextLev(TreeLinkNode* &cur, TreeLinkNode* curNextLev){
        if(cur -> left == curNextLev && cur -> right != NULL){
            return cur -> right;
        }else{
            while(cur -> next != NULL){
                cur = cur -> next;
                if(cur -> left != NULL && cur -> left != curNextLev) return cur -> left;
                if(cur -> right != NULL && cur -> right != curNextLev) return cur -> right;
            }
        }
        return NULL;
    }
    
    TreeLinkNode* findStartNodeNextLev(TreeLinkNode* node){
        if(NULL == node) return NULL;
        if(node -> left != NULL) return node -> left;
        return findNextNodeNextLev(node, node -> left);
    }
};

  

 

Populating Next Right Pointers in Each Node I II

标签:

原文地址:http://www.cnblogs.com/qiaozhoulin/p/4746862.html

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