- 问题
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.
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
- 解答
class Solution { public: void connect(TreeLinkNode *root) { queue<TreeLinkNode *> qu; if(!root) return ; qu.push(root); root->next=NULL; while(!qu.empty()) { int len=qu.size(); for(int i=0;i<len;i++) { TreeLinkNode *temp=qu.front(); qu.pop(); if(i==len-1) temp->next=NULL; else temp->next=qu.front(); if(temp->left) { qu.push(temp->left); } if(temp->right) { qu.push(temp->right); } } //TreeLinkNode *temp1=qu.front(); // temp1->next=NULL; // qu.pop(); } } };
Populating Next Right Pointers in Each Node II
最新推荐文章于 2021-01-29 16:34:55 发布