Leetcode first brush _ Populating Next Right Pointers in Each Node II

Source: Internet
Author: User

It is very natural to promote it. What if we get rid of the condition of a Complete Binary Tree? Because this condition is not critical, it will not affect the overall thinking. The practice is to find the starting point of each layer, and then step by layer.

If it is a Complete Binary Tree, the starting point of each layer is the left child of the upper starting point. The links between brothers are also simple. You can directly find the right and right children of the corresponding father. Generally, the starting point of a binary tree is the first left child with a child node on the upper layer, or the right child without a left child. In order to be continuously linked in the child layer, we must save it as the previous node of the Child layer. When the current layer finds a node with a child, it is connected to the back of the pre node, then update the pre node's point.

class Solution {public:    void connect(TreeLinkNode *root) {        if(root == NULL)    return;        TreeLinkNode *beginNode = root, *leftNode, *pre;        while(beginNode){            leftNode = beginNode;            pre = NULL;            beginNode = NULL;            while(leftNode){                if(leftNode->left&&leftNode->right){                    leftNode->left->next = leftNode->right;                    if(pre)    pre->next = leftNode->left;                    if(!beginNode)  beginNode = leftNode->left;                    pre = leftNode->right;                }else if(leftNode->left){                    if(pre)    pre->next = leftNode->left;                    if(!beginNode)  beginNode = leftNode->left;                    pre = leftNode->left;                }else if(leftNode->right){                    if(pre)    pre->next = leftNode->right;                    if(!beginNode)  beginNode = leftNode->right;                    pre = leftNode->right;                }                leftNode = leftNode->next;            }        }    }};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.