leetcode107-python 二叉树层次遍历

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]
]


解题要点:

1.对二叉树进行层次遍历,但是不能把节点直接放入结果的那个list中,而是把节点的数值放入list中才能得到所求;

# 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]]
        """
        if root == None:
            return []
        st = []
        st.append(root)
        k = []
        k.append(root.val)
        ans = []
        ans.insert(0, k)
        p = st[0]
        while len(st) != 0:
            temp = st[0]
            if temp.left != None:
                st.append(temp.left)
            if temp.right != None:
                st.append(temp.right)

            if p == st[0]:
                p = st[len(st)-1]
                if p != st[0]:
                    k = []
                    for i in range(1, len(st)):
                        k.append(st[i].val)
                    ans.insert(0, k)
                    
            st.pop(0)
        return ans

经过借鉴改进:

1.dfs的过程不是队列中前面元素一个一个弹出,而是遍历一次直接等于下一层的列表;

2.l1 = l1 + [l2]的语法,是可以把l2作为元素加入l1中的,如果是l1 = [l2] + l1 ,则l2是加在l1的前面

# 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]]
        """
        if root == None:
            return []
        queue = []
        queue.append(root)
        ans = []

        while queue:
            nodes = []
            no_val = []

            for i in queue:
                if i.left != None:
                    nodes.append(i.left)
                if i.right != None:
                    nodes.append(i.right)
                no_val += [i.val]
            queue = nodes
            ans = [no_val] + ans
        return ans

你可能感兴趣的:(leetcode)