Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input: 2 / \ 1 3 Output: 1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7
Note: You may assume the tree (i.e., the given root node) is not NULL.
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var findBottomLeftValue = function(root) { var res=new Array(); var queue=new Array(); var bottomLeft; queue.push(root); while(queue.length>0){ var temp=new Array(); while(queue.length>0){ var n=queue.shift(); bottomLeft=n.val; if(n.right!=null){ temp.push(n.right); }if(n.left!=null){ temp.push(n.left); } } queue=temp; } return bottomLeft; };
一道BFS题目,思路就是用一个队列,遍历每层。