[LeetCode] 117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:算法竞赛谜题 编辑:程序博客网 时间:2024/06/05 02:21
Follow up for problem “Populating Next Right Pointers in Each Node“.What if the given tree could be any binary tree? Would your previous solution still work?Note:* You may only use constant extra space.For example,Given the following binary tree,
         1       /  \      2    3     / \    \    4   5    7
After calling your function, the tree should look like:
         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 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);    }};

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

阅读全文
0 0