美文网首页
199. Binary Tree Right Side View

199. Binary Tree Right Side View

作者: exialym | 来源:发表于2016-09-22 14:35 被阅读7次

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
    一颗二叉树,获取从右边看去能看到的每层的第一个节点,就是每层最右侧的节点。
    广度优先遍历,做一点小修改就行:

    var rightSideView = function(root) {
        var result = [];
        if (!root) 
            return result;
        var pre = [root];
        var now = [];
        while (pre.length) {
            result.push(pre[0].val);
            for(var i = 0;i < pre.length ;i++) {
                if (pre[i].right)
                    now.push(pre[i].right);
                if (pre[i].left)
                    now.push(pre[i].left);
            }
            pre = now;
            now = [];
        }
        return result;
    };
    

    相关文章

      网友评论

          本文标题:199. Binary Tree Right Side View

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