513.找树左下角的值
思路
层序遍历
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<List<Integer>> record=new ArrayList<>();
public int findBottomLeftValue(TreeNode root) {
find(root,0);
return record.get(record.size()-1).get(0);
}
public void find(TreeNode node,int deep){
if(node==null) return;
deep++;
if(record.size()<deep){
List<Integer> count=new ArrayList<>();
record.add(count);
}
record.get(deep-1).add(node.val);
find(node.left,deep);
find(node.right,deep);
}
}
112. 路径总和
思路
前序遍历,用找所有路径的方法,计算总和是否是target。同样是前序遍历,可以减去target值,最后返回target值是否为0的判断
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
return find(root,targetSum);
}
public boolean find(TreeNode node,int targetSum){ //同样的壳,更灵活一点
if(node==null) return false;
targetSum-=node.val;
if(node.left==null&&node.right==null){
return targetSum==0;
}
if(node.left!=null){
boolean leftresult=find(node.left,targetSum);
if(leftresult==true) return leftresult;
}
if(node.right!=null){
boolean rightresult=find(node.right,targetSum);
if(rightresult==true) return rightresult;
}
return false;
}
}
106.从中序与后序遍历序列构造二叉树
思路
前序遍历,确定好中间节点,记录划分左右子树的起始节点和终止节点,坚持左闭右开(不然就要踩坑了。。)
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
HashMap<Integer,Integer> record=new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i=0;i<inorder.length;i++){
record.put(inorder[i],i);
}
return find(inorder,0,inorder.length,postorder,0,postorder.length);
}
public TreeNode find(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
if(inBegin>=inEnd || postBegin>=postEnd) return null;
int rootVal=postorder[postEnd-1];
int rootIndex=record.get(rootVal);
int leftNodeLen=rootIndex-inBegin; //要靠左子树的长度去划分右子树
TreeNode root=new TreeNode(rootVal);
TreeNode leftNode=find(inorder,inBegin,rootIndex,postorder,postBegin,postBegin+leftNodeLen); //划分中序和后序的左子树
TreeNode rightNode=find(inorder,rootIndex+1,inEnd,postorder,postBegin+leftNodeLen,postEnd-1);
root.left=leftNode;
root.right=rightNode;
return root;
}
}