zoukankan      html  css  js  c++  java
  • [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).

    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
    

     解题思路:

    按层遍历一遍所有结点即可,每一次从左到右枚举一次当前层的节点(这一层的节点已经连上),如果下一层为空,则退出,否则顺序地将下一层连起来。

    /**
     * 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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
        if(root == NULL)
            return;
            
        TreeLinkNode *head = root, *last = root, *tmp_last = root;//store the horizontal list
        root -> next = NULL;
        
        //if head -> left == NULL, then this is the leaf level, end
        while(head -> left != NULL)
        {
            //list the head level node
            last = head -> left;//last stores the next level, which is what we want to connect
            last -> next = head -> right;//connect the right to the left
            last = head -> right;//last node switch to the right node of the head
            tmp_last = head;//head level last node
            while(tmp_last -> next != NULL)
            {
                tmp_last = tmp_last -> next;
                last -> next = tmp_last -> left;
                (tmp_last -> left) -> next = tmp_last -> right;
                last = tmp_last -> right;
            }
            
            last -> next = NULL;
            head = head -> left;
        } 
        }
    };
  • 相关阅读:
    整理sql server数据类型
    【MVC4升级到MVC5】ASP.Net MVC 4项目升级MVC 5的方法
    MVC学习笔记:入门
    maven第一次创建项目太慢解决方法
    idea中创建maven的Javaweb工程并进行配置
    idea中MavenWeb项目不能创建Servlet的解决办法
    Java模拟客户端向服务器上传文件
    Java学习随笔---常用API(二)
    ssh设置超时时间
    linux 登陆失败处理
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415988.html
Copyright © 2011-2022 走看看