1.二叉树中和为某一值得路径
import java.util.ArrayList;
public class Solution{
private ArrayList<ArrayList<Integer>> listAll=new ArrayList<>();
private ArrayList<Integer> list=new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target){
if(root==null){
return listAll;
}
list.add(root.val);
target-=root.val;
if(target==0&&root.left==null&&root.right==null){
listAll.add(new ArrayList<>(list));
}
FindPath(root.left,target);
FindPath(root.right,target);
list.remove(list.size()-1);
return listAll;
}
}
思路:树的题目一般两种做法:递归和非递归
递归:通常代码量少,而且意图看起来非常清晰明确
非递归:节约空间,代码量多
递归三部曲:
1.明白递归函数功能:FindPath(TreeNode* root,int sum),从root节点出发,找和为sum的路径
2.递归终止条件:当root节点为叶子节点并且sum==root->val,表示找到了一条符合条件的路径
3.下一次递归:如果左子树不空,递归左子树FindPath(root->left,sum-root->val)
如果右子树不空,递归右子树FindPath(root->right,sum-root->val)
2.二叉搜索树和双向链表
import java.util.ArrayList;
public class Solution{
TreeNode pre=null;
public TreeNode Convert(TreeNode pRootOfTree){
if(pRootOfTree==null) return null;
Convert(pRootOfTree.right);
if(pre!=null){
pRootOfTree.right=pre;
pre.left=pRootOfTree;
}
pre=pRootOfTree;
Convert(pRootOfTree.left);
return pre;
}
}
思路:二叉树中序遍历的结果是排好序的,->想到线索化二叉树
线索化二叉树:用一个全局变量去保存前一个节点,然后在去创建节点之间的关系
中序遍历:左根右
3.连续子数组的最大和
public class Solution{
public int FindGreateatSumOfSubArray(int[] array){
if(array==null||array.length==0){
return 0;
}
int sum=0;
int result=array[0];
for(int sum:array){
sum=sum>0?sum+num:num;
result=Math.max(sum,result);
}
return result;
}
}
思路:动态规划
若和小于0,则将最大和置为当前值,
1.当前数字加上一个正数,一定会变大
2.加上一个负数,一定会变小
状态转移方程: result=Math.max(sum,result);