Leetcode "populating next right pointers in each node"

Source: Internet
Author: User

Apparently BFS is the most obvious one .. but it is not that simple-only constant extra space is provided.

Then the only strategy to take is recursion. I bogged down for quite while .. only after checked http://leetcode.com/2010/03/first-on-site-technical-interview.html, I got enlightment:Pick a pen and a piece of paper, and simulate the procedure by drawing-This strategy is working so well on digoal-like problems! Just like"Starting from enumeration and check Pattern"Strategy, a good solution starts from basics.

class Solution {public:    void connect(TreeLinkNode *p) {        if (!p) return;        if (p->left)    p->left->next = p->right;    // with the same parent        if (p->right)    p->right->next = (p->next) ? p->next->left : NULL;        connect(p->left);        connect(p->right);    }};

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.