博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode117. Populating Next Right Pointers in Each Node II(思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 776 字,大约阅读时间需要 2 分钟。

Given a binary tree

struct Node {  int val;  Node *left;  Node *right;  Node *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.


用层序遍历的方式,把每一层节点存在一个list中。

然后进行处理比较容易。

class Solution:    def connect(self, root: 'Node') -> 'Node':        if root is None:return root        level = [root]        root.next=None        while level:            temp=[]            for i in range(len(level)-1):                level[i].next=level[i+1]            for node in level:                if node.left:                    temp.append(node.left)                if node.right:                    temp.append(node.right)            level=temp        return root

 

转载地址:http://qdrbb.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】240-Search a 2D Matrix II
查看>>
【LEETCODE】53-Maximum Subarray
查看>>
【LEETCODE】215-Kth Largest Element in an Array
查看>>
【LEETCODE】241-Different Ways to Add Parentheses
查看>>
【LEETCODE】312-Burst Balloons
查看>>
【LEETCODE】232-Implement Queue using Stacks
查看>>
【LEETCODE】225-Implement Stack using Queues
查看>>
【LEETCODE】155-Min Stack
查看>>
【LEETCODE】20-Valid Parentheses
查看>>
【LEETCODE】290-Word Pattern
查看>>
【LEETCODE】36-Valid Sudoku
查看>>
【LEETCODE】205-Isomorphic Strings
查看>>
【LEETCODE】204-Count Primes
查看>>
【LEETCODE】228-Summary Ranges
查看>>
【LEETCODE】27-Remove Element
查看>>
【LEETCODE】66-Plus One
查看>>
【LEETCODE】26-Remove Duplicates from Sorted Array
查看>>
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
word2vec 模型思想和代码实现
查看>>