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:
- You may only use constant extra space
记录二叉树中每一层的信息,DFS
/**
* 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:
map<int,TreeLinkNode *> m;
void conn(TreeLinkNode *root,int level){
if(level==1||m.find(level)==m.end()) m.insert(pair<int,TreeLinkNode *>(level, root));
else{
m[level]->next = root;
m[level] = root;
}
if(root->left!=NULL) conn(root->left,level+1);
if(root->right!=NULL) conn(root->right,level+1);
}
void connect(TreeLinkNode *root) {
if(root == NULL) return;
conn(root,1);
}
};