Skip to content

Latest commit

 

History

History
121 lines (95 loc) · 2.4 KB

107. Binary Tree Level Order Traversal II.md

File metadata and controls

121 lines (95 loc) · 2.4 KB

107. Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example: Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

Solution

code1还是102. Binary Tree Level Order Traversal的套路emmmm

code2是dfs的思路,很机智,太久没写了手生要多练!

Code1

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        result = []
        if root is None:
            return result
        node = root
        stack = []
        stack2 = []
        levelstack = []
        numstack = []
        stack.append(node)
        stack2.append(0)
        while stack:
            node = stack.pop(0)
            node_level = stack2.pop(0)
            if node.left:
                stack.append(node.left)
                stack2.append(node_level+1)
            if node.right:
                stack.append(node.right)
                stack2.append(node_level+1)
            numstack.append(node.val)
            levelstack.append(node_level)
            
        max_level = max(levelstack)
        for i in range(0,max_level+1):
            result.append([])
        
        max_depth = max(levelstack)
        for i,c in enumerate(numstack):
            result[max_depth-levelstack[i]].append(c)
        return result

Code2

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

def dfs(root,level,res):
    if root is None:
        return
    if level > len(res):
        res.insert(0,[])
    res[-level].append(root.val)
    if root.left:
        dfs(root.left,level+1,res)
    if root.right:
        dfs(root.right,level+1,res)

class Solution:
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        if root is None:
            return res
        dfs(root,1,res)
        return res