动态规划和树的题(2021-7-21)

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值