[leetcode] Populating Next Right Pointers in Each Node II

1144 단어
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) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
        if(!root)
            return;
		TreeLinkNode** array=new TreeLinkNode*[10000];
		array[0]=root;
		int p,q,flag;
		for(p=0,q=1,flag=1 ; p!=q ; p++ ){
			if(p==flag){
				for(int i=p ; i<q-1 ; i++){
					array[i]->next=array[i+1];
				}
				flag=q;
			}
			if(array[p]->left)
				array[q++]=array[p]->left;
			if(array[p]->right)
				array[q++]=array[p]->right;
		}
	}
};

좋은 웹페이지 즐겨찾기