---恢复内容开始---

题目描述:

leetcode-117-填充每个节点的下一个右侧节点指针②

leetcode-117-填充每个节点的下一个右侧节点指针②

 

 

 方法一:层次遍历

"""
# Definition for a Node.
class Node:
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return
        stack = [root]
        #ans = []
        while stack:
            tem_stack=[]
            #tem_ans = []
            for i in stack:
                tem_ans.append(i.val)
                if i.left:
                    tem_stack.append(i.left)
                if i.right:
                    tem_stack.append(i.right)
            if len(tem_stack)>1:
                for i in range(len(tem_stack)-1):
                    tem_stack[i].next = tem_stack[i+1]
            stack = tem_stack
            #ans.append(tem_ans)
        return root

方法二:迭代

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        cur = root 
        head = None 
        tail = None 
        while cur: 
            while cur: 
                if cur.left: 
                    if not head: 
                        head = cur.left 
                        tail = cur.left 
                    else: 
                        tail.next = cur.left 
                        tail = tail.next 
                if cur.right: 
                    if not head: 
                        head = cur.right 
                        tail = cur.right 
                    else: 
                        tail.next = cur.right 
                        tail = tail.next 
                cur = cur.next 
            cur = head 
            head = None 
            tail = None 
        return root

 

---恢复内容结束---

相关文章:

  • 2022-02-23
  • 2021-06-25
  • 2021-05-29
  • 2021-11-01
  • 2021-10-22
  • 2021-11-01
  • 2022-12-23
  • 2021-12-02
猜你喜欢
  • 2021-11-07
  • 2021-04-02
  • 2021-08-15
  • 2021-06-11
  • 2021-07-06
  • 2021-06-15
相关资源
相似解决方案