要找到二叉树的最大深度,才能更新res值,遍历采用左右,这样就能先遍历左结点,如果没有左节点再更新右结点
class Solution {
int maxDepth=0;
int res;
public void travel(TreeNode root,int Depth){
if(root.left==null&&root.right==null){
if(Depth>maxDepth){
maxDepth=Depth;
res= root.val;
}
return;//遍历到叶子节点就结束
}
if(root.left!=null){
Depth++;
travel(root.left,Depth);//递
Depth--;//回溯
}
if(root.right!=null){
Depth++;
travel(root.right,Depth);//递
Depth--;//回溯
}
}
public int findBottomLeftValue(TreeNode root) {
travel(root,1);
return res;
}
}
路径总和
主要是找到了路径就直接返回true,递归的递前进行运算的话,归后要做逆运算。
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
targetSum-=root.val;
if(root.left==null&&root.right==null&&targetSum==0) return true;
if(root.left!=null){
boolean left=hasPathSum(root.left,targetSum);
if(left) return true;
}
if(root.right!=null){
boolean right=hasPathSum(root.right,targetSum);
if(right) return true;
}
return false;
}
}