标签:breadth-first search leetcode depth-first search
题目:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
For example,
Given the following binary tree,
1 / 2 3 / \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ 4-> 5 -> 7 -> NULL
思路:这次我们要链接的不是完全二叉树,题目依然要求我们使用常数空间复杂度。我们需要多维护两个变量,总共四个变量。
lasthead = curhead; //移动到下一层 curhead = NULL; //重置curhead;
/** * 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; TreeLinkNode* lasthead = root; //维护上一层的链表开始的节点 TreeLinkNode* pre = NULL; //维护前一个结点 TreeLinkNode* curhead = NULL; //维护当前层的链表开始的节点 while(lasthead) { TreeLinkNode* lastCur = lasthead; //lastcur从上一层链表的开始节点开始 while(lastCur) { if(lastCur->left) { if(curhead == NULL) { curhead = lastCur->left; //如果还没确定该行的头结点,在碰到第一个非空节点时确定 pre = curhead; } else { pre->next = lastCur->left; pre = pre->next; } } if(lastCur->right) { if(curhead == NULL) { curhead = lastCur->right; pre = curhead; } else { pre->next = lastCur->right; pre = pre->next; } } lastCur = lastCur->next; //移动到下一个节点 } lasthead = curhead; //移动到下一层 curhead = NULL; //重置curhead; } } };
[C++]LeetCode: 124 Populating Next Right Pointers in Each Node II(链接二叉树)
标签:breadth-first search leetcode depth-first search
原文地址:http://blog.csdn.net/cinderella_niu/article/details/43151057