标签:
题目来自:LeetCode
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
Given a binary tree
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
.
Initially, all next pointers are set to NULL
.
Note:
For example,
Given the following perfect binary tree,
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
/** * 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: void connect(TreeLinkNode *root) { if(root==NULL||(root->left==NULL&&root->right==NULL)) return ; queue<TreeLinkNode *> queue0; queue0.push(root); queue<TreeLinkNode *> queue1; TreeLinkNode * pre; int op01=0; while(!queue0.empty()||!queue1.empty()) { if(op01==0) { pre=queue0.front(); queue0.pop(); if(pre->left!=NULL) queue1.push(pre->left); if(pre->right!=NULL) queue1.push(pre->right); while(!queue0.empty()) { pre->next=queue0.front(); if(queue0.front()->left!=NULL) queue1.push((queue0.front())->left); if(queue0.front()->right!=NULL) queue1.push(queue0.front()->right); pre=queue0.front(); queue0.pop(); } op01=1; } else{ pre=queue1.front(); queue1.pop(); if(pre->left!=NULL) queue0.push(pre->left); if(pre->right!=NULL) queue0.push(pre->right); while(!queue1.empty()) { pre->next=queue1.front(); // cout<<queue1.front()->left->val; if((queue1.front()->left)!=NULL) queue0.push(queue1.front()->left); if(queue1.front()->right!=NULL) queue0.push(queue1.front()->right); pre=queue1.front(); queue1.pop(); } op01=0; } } return ; } };
Populating Next Right Pointers in Each Node Total Accepted: 46429 Total Submissions: 128383
标签:
原文地址:http://blog.csdn.net/zhouyelihua/article/details/45219701