[leetcode]Populating Next Right Pointers in Each Node II

来源:互联网 发布:aft3登陆器源码 编辑:程序博客网 时间:2024/05/29 15:14

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);    }};
0 0
原创粉丝点击