python 短小精悍,golang 簡單高效
題面
從上到下列印出二叉樹的每個節點,同一層的節點按照從左到右的順序列印。
給定二叉樹 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回
[3,9,20,15,7]
python
- 佇列 邊進邊出
def levelOrder(root: TreeNode) -> List[int]: rs = [] q = [root] while len(q): cur = q.pop(0) cur and rs.append(cur.val) cur and cur.left and q.append(cur.left) cur and cur.right and q.append(cur.right) return rs
golang
- 層序遍歷 層層遞進
func levelOrder(root *TreeNode) []int { var rs []int for level :=[]*TreeNode{root};len(level)>0;{ tmp := make([]*TreeNode, 0) for i:=0;i<len(level);i++{ if level[i] != nil { rs = append(rs, level[i].Val) if level[i].Left != nil { tmp = append(tmp, level[i].Left) } if level[i].Right != nil{ tmp = append(tmp, level[i].Right) } } } level=tmp } return rs }
效能
本作品採用《CC 協議》,轉載必須註明作者和本文連結