美文网首页
Binary Tree Level Order Traversa

Binary Tree Level Order Traversa

作者: sunner168 | 来源:发表于2017-08-13 23:18 被阅读7次

    题目

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

      3
       / \
      9  20
        /  \
       15   7
    

    return its level order traversal as:

    [
      [3],
      [9,20],
      [15,7]
    ]
    

    python 答案

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            result = []
            if not root:
                return result
            queue = [root]
            while queue:
                new_q = []
                result.append([x.val for x in queue])
                for node in queue:
                    if node.left:
                        new_q.append(node.left)
                    if node.right:
                        new_q.append(node.right)
                queue = new_q
            return result
    

    js答案

    /**
     * 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) {
        var result =[],queue = [];
        if(!root){
            return result
        }
        queue.push(root);
        while(queue.length > 0){
           var currentLevel = [ ];
            //current
            var size = queue.length;
            for(var i = 0; i<size; i++){
                
                var element = queue.shift();
                 currentLevel.push(element.val)
                if(element.left){
                    queue.push(element.left)
                }
               
                if(element.right){
                    queue.push(element.right)
                }
                
            }
            result.push(currentLevel)
        }
        return result
    };
    

    相关文章

      网友评论

          本文标题:Binary Tree Level Order Traversa

          本文链接:https://www.haomeiwen.com/subject/jacyrxtx.html