找树左下角的值
看完题后的思路
f(root,深度)
if(为叶子节点&&深度最大)
加入结果;
返回
if(左不为空)
遍历左子树
if(右不为空)
遍历右子树
代码
// day18
//|513.找树左下角的值
int findBottomLeftValueRes=0;
int findBottomLeftValuemaxdepth=0;
public int findBottomLeftValue(TreeNode root) {
if (root==null){
return -1;
}
findBottomLeftValue(root,1);
return findBottomLeftValueRes;
}
public void findBottomLeftValue(TreeNode root,int depth){
if(root==null){
return;
}
if (root.left==null&&root.right==null&&depth>findBottomLeftValuemaxdepth){
findBottomLeftValuemaxdepth=depth;
findBottomLeftValueRes=root.val;
return;
}
findBottomLeftValue(root.left,depth+1);
findBottomLeftValue(root.right,depth+1);
}
复杂度
收获
当终止条件为叶子节点时的写法
if(root==null){// 加这一句是为了下面不用判断
return;
}
if (root.left==null&&root.right==null&&depth>findBottomLeftValuemaxdepth){
findBottomLeftValuemaxdepth=depth;
findBottomLeftValueRes=root.val;
return;
}
findBottomLeftValue(root.left,depth+1);
findBottomLeftValue(root.right,depth+1);
三刷敲出来
112. 路径总和
看完题后的思路
回朔算法
- bool f(root,sum)
- 终止条件
sum=sum-value;
if(sume==0&&叶子节点){
return true;
} - left=f(左,sum值)
right=f(右,sum)
代码
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root==null){
return false;
}
targetSum-=root.val;
if (targetSum==0&&root.left==null&&root.right==null){
return true;
}
if (root.left!=null){
boolean left = hasPathSum(root.left, targetSum);
if (left){
return left;
}
}
if (root.right!=null){
boolean right = hasPathSum(root.right, targetSum);
return right;
}
return false;
}
复杂度
收获
过
113.路径总和ii
看完题后的思路
先加入节点的回溯
List<List<Integer>> pathSumRes=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if (root==null){
return pathSumRes;
}
pathSumTB(root,targetSum,new ArrayList<>());
return pathSumRes;
}
public void pathSumTB(TreeNode root, int targetSum,List<Integer> path) {
path.add(root.val);
targetSum-=root.val;
if (root.left==null&&root.right==null&&targetSum==0){
ArrayList<Integer> list = new ArrayList<>(path);
pathSumRes.add(list);
return;
}
if (root.left!=null){
pathSumTB(root.left,targetSum,path);
path.remove(path.size()-1);
}
if (root.right!=null){
pathSumTB(root.right,targetSum,path);
path.remove(path.size()-1);
}
}
收获
三刷过
106. 从中序与后序遍历序列构造二叉树
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode treeNode = buildTree(inorder, 0, inorder.length, postorder, 0, postorder.length);
return treeNode;
}
public TreeNode buildTree(int[] inorder,int ileft,int iright, int[] postorder,int pleft,int pright){
if (ileft==iright){
return null;
}
int rootVal=postorder[pright-1];
TreeNode root = new TreeNode(rootVal);
int mid = getByIterm(inorder, rootVal, ileft, iright);
TreeNode left = buildTree(inorder, ileft, mid, postorder, pleft, pleft + mid-ileft);
TreeNode right = buildTree(inorder, mid + 1, iright, postorder, pleft + mid - ileft ,pright - 1);
root.left=left;
root.right=right;
return root;
}
public int getByIterm(int[] num,int target,int left,int right) {
for (int i = left; i <right ; i++) {
if (num[i]==target){
return i;
}
}
return -1;
}
收获
三刷过一遍