这道题的要求是寻找最深的一层中最靠左的节点的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;
}
}
}
};