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.
目的是找到树的最下层最左边的节点的值,并不是返回目标节点。这样就可以简化返回的对象(我的解法返回的是目标节点而不是值,增加了内存开销)
这个问题,一看,直观的就是一层一层往下搜索,最直观的就是递归的解法。因为要求有两个
1. 最下层
2. 最左边
那么递归返回的应该有两个值,一个是节点到根的距离,一个是目标值,这样就可以将返回的结果封装起来。
看我的解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
class Bean{
int height;
TreeNode node;
Bean( TreeNode p, int x){height = x; node = p;}
}
public int findBottomLeftValue(TreeNode root) {
Bean res = getLeftMost(root, 0);
return res.node.val;
}
Bean getLeftMost(TreeNode root, int h){
if(root ==null) return null;
Bean left = getLeftMost(root.left, h+1);
Bean right = getLeftMost(root.right, h+1);
if(left==null&&right==null) return new Bean(root, h);
if(left!=null&&right==null) return left;
if(left==null&&right!=null) return right;
if(left.height >= right.height){
return left;
}else{
return right;
}
}
}
看看top answer
public class Solution {
int ans=0, h=0;
public int findBottomLeftValue(TreeNode root) {
findBottomLeftValue(root, 1);
return ans;
}
public void findBottomLeftValue(TreeNode root, int depth) {
if (h<depth) {ans=root.val;h=depth;}
if (root.left!=null) findBottomLeftValue(root.left, depth+1);
if (root.right!=null) findBottomLeftValue(root.right, depth+1);
}
}
No global variables, 6ms (faster):
public class Solution {
public int findBottomLeftValue(TreeNode root) {
return findBottomLeftValue(root, 1, new int[]{0,0});
}
public int findBottomLeftValue(TreeNode root, int depth, int[] res) {
if (res[1]<depth) {res[0]=root.val;res[1]=depth;}
if (root.left!=null) findBottomLeftValue(root.left, depth+1, res);
if (root.right!=null) findBottomLeftValue(root.right, depth+1, res);
return res[0];
}
}
思路是一样,但是将返回结果封装在了一个数组中!
这里指的注意的是h