199. Binary Tree Right Side View

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)