zoukankan      html  css  js  c++  java
  • 117. Populating Next Right Pointers in Each Node II

    问题描述:

    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.
    • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

    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

    解题思路:

    这道题要求我们用O(1)的空间复杂度,那么很显然,队列是不能再用的。

    那我们可以用指针来遍历。

    这里很巧妙的一点是:在我当前的节点我去连接前一个节点和现在的节点,因为我也不知道下一个离当前节点最近的节点是哪一个节点。

    而判断该节点是否为这一层的头节点也十分巧妙:看前一个节点是不是不存在

    代码:

    /**
     * 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) {
            TreeLinkNode* head = NULL;
            TreeLinkNode* prev = NULL;
            TreeLinkNode* cur = root;
            
            while(cur){
                while(cur){
                    if(cur->left){
                        if(prev) prev->next = cur->left;
                        else head = cur->left;
                        prev = cur->left;
                    }
                    if(cur->right){
                        if(prev) prev->next = cur->right;
                        else head = cur->right;
                        prev = cur->right;
                    }
                    cur = cur->next;
                }
                cur = head;
                head = NULL;
                prev = NULL;
            }
        }
    };
  • 相关阅读:
    Linux命令学习—— fdisk -l 查看硬盘及分区信息
    UE4 Runtime下动态给Actor添加组件
    如何批量下载网站网页
    ue4 motage
    帧同步相关
    张瀚荣:如何用UE4制作3D动作游戏
    游戏服务器架构演进(完整版)
    Digital Mike头发制作及渲染的深度揭秘
    [UE4]如何替换角色Mesh上的Material材质
    [UE4]用C++如何创建Box Collision
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9348943.html
Copyright © 2011-2022 走看看