Populating Next Right Pointers in Each Node II

来源:互联网 发布:极限挑战2网络直播 编辑:程序博客网 时间:2024/04/27 21:34

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

码好一次性通过~~ yeah~

思路是很明显的,一层一层的找,利用当前层的next来figure out下一层的next

第一次做的时候用了queue来完成的按层遍历,这次才看到了 O(1)的空间复杂度。

重新写了一下,为了看起来思路清楚点,代码写的略长。

/** * 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:    TreeLinkNode* myNextLine(TreeLinkNode *cur){        if(cur -> left) return cur -> left;        if(cur -> right) return cur -> right;                while(cur -> next){            cur = cur -> next;            if(cur -> left) return cur -> left;            if(cur -> right) return cur -> right;        }                return NULL;    }    TreeLinkNode* myleftnext(TreeLinkNode *cur){        if(cur -> right) return cur -> right;                while(cur -> next){            cur = cur -> next;            if(cur -> left) return cur -> left;            if(cur -> right) return cur -> right;        }                return NULL;    }        TreeLinkNode* myrightnext(TreeLinkNode *cur){        while(cur -> next){            cur = cur -> next;            if(cur -> left) return cur -> left;            if(cur -> right) return cur -> right;        }                return NULL;    }        void connect(TreeLinkNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(!root) return;                TreeLinkNode *cur = root;        TreeLinkNode *nextLine = myNextLine(cur);                while(nextLine){            while(cur){                if(cur -> left){                    cur -> left -> next = myleftnext(cur);                }                if(cur -> right){                    cur -> right -> next = myrightnext(cur);                }                                                cur = cur -> next;            }            cur = nextLine;            nextLine = myNextLine(cur);        }            }};



原创粉丝点击