leetcode之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:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

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
意思就是:

给定一棵满二叉树,要使在一个平面上的每个节点的next指针指向该节点的右方的节点,如果没有,则指向NULL.

解体思路:

由于是满二叉树, 所以对于每个节点, 如果该节点是父亲的左孩子,则它的next指向父亲的右子树; 如果该节点是父亲的右孩子,则它的next指向该节点父亲的next的左孩子.

代码如下:

/**
 * 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){
				return;
			}
			root->next = NULL;
			queue<TreeLinkNode*> storage;
			storage.push(root);
			while(!storage.empty()){
				TreeLinkNode* current = storage.front();
				storage.pop();
				if(current->left){
					current->left->next = current->right;
				}
				if(current->next && current->right){
					current->right->next = current->next->left;
				}
				else if(current->right){
					current->right->next = NULL;
				}
				if(current->left){
					storage.push(current->left);
				}
				if(current->right){
					storage.push(current->right);
				}
			}
    }
};


你可能感兴趣的:(LeetCode,C++,算法)