zoukankan      html  css  js  c++  java
  • [LeetCode]Populating Next Right Pointers in Each Node

    题目链接: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).

    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

    题目解法:

    这道题本来只是一道简单的计层BFS题目,但是有一个对于常数额外空间复杂度的要求,因此不能使用传统的队列BFS,可以只定义一个变量cur,根据树的性质来完成BFS,具体方法如下:

    首先初始化cur为root,cur的每次动作是从左到右的,通过cur = cur->next实现;当cur->next==NULL时,让cur沿着root的左子树往下走,也就是root = root->left; cur = root;当我们设置next时,实际上我们是设置的下一层的next,因此当访问当前层的next时,已经被设置过。

    下面举个例子,如上面一棵完全二叉树,假设现在cur=2,在第一层我们已经设置了2的next为3,因此在本层通过cur->left->next=cur->right设置4->5,因为cur->next!=NULL,因此我们设置cur->right->next=cur->next->left,也就是2的右子树5指向3的左子树6,然后cur=3,继续操作。

    代码如下:

    /**
     * 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 == NULL) return;
            TreeLinkNode *cur;
            while(root->left != NULL){
                cur = root;
                while(cur != NULL){
                    cur->left->next = cur->right;
                    if(cur->next != NULL)
                        cur->right->next = cur->next->left;
                    cur = cur->next;
                }
                root = root->left;
            }
        }
    };


  • 相关阅读:
    <a>标签实现锚点跳跃,<a>标签实现href不跳跃另外加事件(ref传参)
    ThinkPHP实现事务回滚示例代码(附加:PDO的事务处理)
    python 命令执行文件传递参数
    python os.walk()
    python sys.stdin、sys.stdout和sys.stderr
    Python 为什么sys.stdout.write 输出时后面总跟一个数字
    python 不同集合上元素的迭代 chain()
    Python zip() 处理多于两个序列的参数, 存储结对的值
    Python 成对处理数据 zip()
    python 同时迭代多个序列
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154019.html
Copyright © 2011-2022 走看看