Populating Next Right Pointers in Each Node IInode
解法一:递归,DFS。由于不是完美二叉树因此子树有可能残缺,故须要平行扫描父节点同层的节点,找到他们的左右子节点。而后右节点就是找到的节点,左节点就是若是右节点存在就选右节点不然选找到的节点code
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() {} Node(int _val, Node* _left, Node* _right, Node* _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public: Node* connect(Node* root) { if(!root) return NULL; Node* p = root->next; while (p) { if (p->left) { p = p->left; break; } if (p->right) { p = p->right; break; } p = p->next; } if(root->right) root->right->next = p; if(root->left) root->left->next = root->right ? root->right : p; connect(root->right); connect(root->left); return root; } };
解法二:非递归。和Populating Next Right Pointers in Each Node - LeetCode如出一辙htm
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() {} Node(int _val, Node* _left, Node* _right, Node* _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public: Node* connect(Node* root) { if(!root) return NULL; queue<Node*> q; q.push(root); while(!q.empty()) { int size = q.size(); for(int i = 0;i < size;i++) { Node* temp = q.front();q.pop(); if(i != size-1) temp->next = q.front(); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } } return root; } };