Given a binary treenode
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.spa
Initially, all next pointers are set to NULL
.指針
Note:code
For example,
Given the following perfect binary tree,blog
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:隊列
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
題目要求是一個二叉樹每一個節點包含三個指針元素,每一個節點除了左子樹和右子樹,還有一個指向其同層次的相鄰右側節點,it
若同層次右側沒有節點,則將next設置爲空,不然將next設置爲右側相鄰節點。io
解決思路:function
一次對每一個節點進行遍歷,若左右子樹不爲空,則將左子樹的next指向右子樹,若該節點的next爲空,則將右子樹的next設置爲空(看圖分析)class
若該節點的next不爲空,則指向與該節點同層次中相鄰的右側節點的左子樹(看圖分析)
這裏使用一個隊列,將根節點先放入隊列,從隊列中取出一個節點node,node移除隊列,node子樹的next節點處理按照上面分析操做。
代碼以下:
1 /** 2 * Definition for binary tree with next pointer. 3 * struct TreeLinkNode { 4 * int val; 5 * TreeLinkNode *left, *right, *next; 6 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 void connect(TreeLinkNode *root) { 12 if(root == NULL) return; 13 queue<TreeLinkNode *> q; 14 15 root->next = NULL; 16 17 q.push(root); 18 19 while(!q.empty()){ 20 TreeLinkNode *node = q.front(); 21 q.pop(); 22 23 if(node->left != NULL && node->right != NULL){ 24 q.push(node->left); 25 q.push(node->right); 26 27 node->left->next = node->right; 28 if(node->next == NULL) 29 node->right->next = NULL; 30 else{ 31 TreeLinkNode *node_next = q.front(); 32 node->right->next = node_next->left; 33 } 34 35 } 36 37 } 38 39 } 40 };