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
    
    

     

    分析

    首先要注意的是题目中给出的Note,我们可以假定所有输入的树都是一颗完全二叉树,既保证所有的非子节点都有左右两个子节点。 在这个假定下,我们在进行循环操作时可以方便很多。可以先设置好next指针,然后通过next指针访问其兄弟节点。
    # Definition for a  binary tree node
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    #         self.next = None
    class Solution:
        # @param root, a tree node
        # @return nothing
        def connect(self, root):
            if not root:
                return None
            last = root
            cur = root
            while last.left: # 保证其不是叶节点
                cur = last
                while cur:
                    cur.left.next = cur.right
                    if cur.next:
                        # 当前节点右节点的下一个指向当前节点下一个的左节点
                        cur.right.next = cur.next.left 
                    cur = cur.next
                last = last.left
            return None
     
  • 相关阅读:
    Spring Boot Devtools 热部署依赖
    SpringBoot 整合 thymeleaf
    spring boot 静态资源的映射规则 (3) 欢迎页面映射
    spring boot 静态资源的映射规则 (2) 替他资源映射
    spring boot 静态资源的映射规则 (1) webjars 资源映射
    css初始化minireset.css
    php递归函数细节
    php的递归函数示例
    php正则字符串提取汉字
    Javascript中的Callback方法浅析
  • 原文地址:https://www.cnblogs.com/No-body/p/4207218.html
Copyright © 2011-2022 走看看