[leetcode]513. Find Bottom Left Tree Value

这道题的要求是寻找最深的一层中最靠左的节点的value。

分析一下题目,优先的节点应该是深度最深的节点,只要这个节点的深度大于所有的节点,就算它是某个节点的右边右边右边节点,那么也应该返回这个节点的值。其次,在几个节点深度相同的时候,我们应该选择最左边的那个。

根据这个思路,代码如下:

var findBottomLeftValue = function(root) {
    var nodeLeftest = root;
    var theMaxDepth = 1;
    var thePrime = 0;
    findMaxLeftDepth(root,1,0);
    return nodeLeftest.val;

    function findMaxLeftDepth(node,nodeDepth,primary){
        var left = node.left;
        var right = node.right;
        if(left){
            findMaxLeftDepth(left,nodeDepth+1,primary+1);
        }
        if(right){
            findMaxLeftDepth(right,nodeDepth+1,primary);
        }
        if(left === null && right === null){
            if(nodeDepth>theMaxDepth){
                theMaxDepth = nodeDepth;
                nodeLeftest = node;
            }
            if(nodeDepth >= theMaxDepth && primary>thePrime){
                thePrime = primary;
                nodeLeftest = node;
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值