题目:
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.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
//给定二叉树,找出最下一层最左边的叶子结点的值。
//思路:根据左右子树的depth来判定最深的叶子节点
if(root.left==null&&root.right==null){
return root.val;
}
if(depth(root.left)>=depth(root.right)){
return findBottomLeftValue(root.left);
}else if(depth(root.left)<depth(root.right)){
return findBottomLeftValue(root.right);
}
return root.val;
}
public int depth(TreeNode root){
if(root==null) return 0;
int right=depth(root.right)+1;
int left=depth(root.left)+1;
return Math.max(right,left);
}
}
分析2(参考答案):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int deep=0;
public int res=0;
public int findBottomLeftValue(TreeNode root) {
//给定二叉树,找出最下一层最左边的叶子结点的值。
//思路:定义公共变量,来记录当前是否大于depth,同时记录res结果
backtrace(root,1);
return res;
}
public void backtrace(TreeNode root,int depth){
if(root!=null){
if(deep<depth){
deep=depth;
res=root.val;
}
//递归左右孩子,因为同一层的总是先遍历left
backtrace(root.left,depth+1);
backtrace(root.right,depth+1);
}
}
}