标签:
乍一看很难,理清思路后很简单的。
/** * 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