Tree - 107. Binary Tree Level Order Traversal II

2020-09-23 17:30:03 浏览数 (1)

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

代码语言:javascript复制
    3
   / 
  9  20
    /  
   15   7

return its bottom-up level order traversal as:

代码语言:javascript复制
[
  [15,7],
  [9,20],
  [3]
]

思路:

层序遍历二叉树,倒序输出,很简单的实现题,使用slice当做队列就可以。

代码:

go:

代码语言:javascript复制
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrderBottom(root *TreeNode) [][]int {
    var res, out [][]int
    if root == nil {return out}
    
    var curQ = []*TreeNode{root}
    var nextQ []*TreeNode
    var level []int
    
    for len(curQ) != 0 {
        for len(curQ) != 0 {
            cur := curQ[0]
            curQ = curQ[1:]
            level = append(level, cur.Val)
            if cur.Left != nil {
                nextQ = append(nextQ, cur.Left)
            }        
            if cur.Right != nil {
                nextQ = append(nextQ, cur.Right)
            }
        }
        curQ = nextQ
        nextQ = nil
        out = append(out, level)
        level = nil
    }
    
    for i := len(out) -1; i >= 0; i-- {
        res = append(res, out[i])
    }
    return res
}

0 人点赞