剑指offer32||-.从上到下打印二叉树||

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [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
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章