LeetCode 문제: Populating Next Right Pointers in Each Node I and II

4812 단어 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).

  • Populating Next Right Pointers in Each Node II


    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

    생각:
    트리를 광범위하게 우선 검색하면 됩니다.
    문제:
    /**
     * 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 == nullptr)
                return;
            
            queue<pair<TreeLinkNode*, int>> traverse;
            traverse.push(make_pair(root, 0));
            while(!traverse.empty())
            {
                auto data = traverse.front();
                traverse.pop();
                
                if (data.first->left != nullptr)
                    traverse.push(make_pair(data.first->left, data.second + 1));
                if (data.first->right != nullptr)
                    traverse.push(make_pair(data.first->right, data.second + 1));
                
                if (traverse.empty() || traverse.front().second != data.second)
                    data.first->next = nullptr;
                else
                    data.first->next = traverse.front().first;
            }
        }
    };

    생각:
    아까 공간 복잡도를 고려하지 않은 요구는 O(1)였다.사실 검색에 귀속 등 수법이 불가피하다. 이런 창고의 공간 복잡도는 바로 O(log N)이고 N은 나무 깊이이다.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 == nullptr)
                return;
            
            if (root->left != nullptr)
                root->left->next = root->right;
            
            if (root->right != nullptr && root->next != nullptr)
                root->right->next = root->next->left;
            else if (root->right != nullptr)
                root->right->next = nullptr;
                
            connect(root->left);
            connect(root->right);
        }
    };
    /**
     * 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* node) {
            if (node == nullptr)
                return;
                
            if (node->left && node->right)
                node->left->next = node->right;
            
            TreeLinkNode* child = node->left;
            if (node->right) child = node->right;
            
            if (child != nullptr)
            {
                TreeLinkNode* i = node->next;
                while( i != nullptr && i->left == nullptr && i->right == nullptr)
                    i = i->next;
                
                if (i != nullptr)
                {
                    if (i->left)
                        child->next = i->left;
                    else
                        child->next = i->right;
                }
            }
            
            // This is critical since we need the right hand side
            // next is ready before the left hand side
            if (node->right) connect(node->right);
            if (node->left) connect(node->left);
        }
    };

    좋은 웹페이지 즐겨찾기