두 갈래 나무를 정해 제자리에서 그것을 단일 체인 테이블로 전개한다.

3286 단어
예를 들어, 지정된 두 갈래 트리
    1
   / \
  2   5
 / \   \
3   4   6
1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
python:( : )
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        preordList = list()
        def preorderTraversal(root):
            if root:
                preordList.append(root)
                preorderTraversal(root.left)
                preorderTraversal(root.right)
        preorderTraversal(root)
        size = len(preordList)
        for i in range(1,size):
            prev,curr = preordList[i-1],preordList[i]
            prev.left = None
            prev.right = curr

go:
func flatten(root *TreeNode)  {
    list := preorderTraversal(root)
    for i := 1; i < len(list); i++ {
        prev, curr := list[i-1], list[i]
        prev.Left, prev.Right = nil, curr
    }
}

func preorderTraversal(root *TreeNode) []*TreeNode {
    list := []*TreeNode{}
    if root != nil {
        list = append(list, root)
        list = append(list, preorderTraversal(root.Left)...)
        list = append(list, preorderTraversal(root.Right)...)
    }
    return list
}

좋은 웹페이지 즐겨찾기