[LeetCode] 116. Populating Next Right Pointers in Each Node

来源:互联网 发布:windows 8.1 sdk 编辑:程序博客网 时间:2024/06/07 07:29
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
class Solution {public:    void connect(TreeLinkNode *root) {        vector<TreeLinkNode *> nxts;        connecthelper(root, nxts, 0);    }private:    void connecthelper(TreeLinkNode *root, vector<TreeLinkNode *> &nxts, int depth) {        if (root == nullptr) return;        if (depth >= nxts.size()) {            nxts.push_back(root);            //root->next = nullptr;        } else {            root->next = nxts[depth];            nxts[depth] = root;        }        connecthelper(root->right, nxts, depth + 1);        connecthelper(root->left, nxts, depth + 1);    }};

这里写图片描述
这里写图片描述

//由于题干中给定了最特殊的满二叉树,所以借此进行优化。class Solution {public:    void connect(TreeLinkNode *root) {        if (root == nullptr) return;        connecthelper(root->left, root, true);        connecthelper(root->right, root, false);    }private:    void connecthelper(TreeLinkNode *root, TreeLinkNode *parent, bool leftchild) {        if (root == nullptr) return;        root->next = leftchild ? parent->right : (parent->next ? parent->next->left : nullptr);        connecthelper(root->left, root, true);        connecthelper(root->right, root, false);    }};

这里写图片描述
这里写图片描述

阅读全文
0 0
原创粉丝点击