從上到下按層打印二叉樹,同一層的節點按從左到右的順序打印,每一層打印到一行。
例如:
給定二叉樹: [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其層次遍歷結果:
[
[3],
[9,20],
[15,7]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
這題有兩種思路,普遍的思路是利用隊列來實現
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
let res=[],list=[];
if(!root)
return res;
list.push(root)
while(list.length>0){
let count=list.length,tmp=[];
for(let i=0;i<count;i++){
let p=list.shift();
tmp.push(p.val);
if(p.left)
list.push(p.left)
if(p.right)
list.push(p.right)
}
res.push(tmp)
}
return res;
};
這裏給出遞歸的代碼
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res=[]
if not root:
return res
def bfs(depth,root):
if depth==len(res):
res.append([])
res[depth].append(root.val)
if root.left:
bfs(depth+1,root.left)
if root.right:
bfs(depth+1,root.right)
bfs(0,root)
return res