先分层遍历,再对结果进行翻转
func levelOrderBottom( root *TreeNode ) [][]int { // write code here if root == nil { return nil } ret := make([][]int, 0) stack := []*TreeNode{root} // 先分层遍历 for len(stack) >0 { size := len(stack) tmp := make([]int, 0, size) for i:=0; i< size; i++{ node := stack[i] tmp = append(tmp, node.Val) if node.Left != nil { stack = append(stack, node.Left) } if node.Right != nil { stack = append(stack, node.Right) } } stack = stack[size:] ret = append(ret, tmp) } // 最后对结果进行翻转 if len(ret) > 0 { for i, j := 0, len(ret)-1; i<j; i,j = i+1, j-1 { ret[i], ret[j] = ret[j], ret[i] } } return ret }