剑指offer第四周

46.二叉搜索树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。

如果是则返回true,否则返回false。

假设输入的数组的任意两个数字都互不相同。

样例
输入:[4, 8, 6, 12, 16, 14, 10]

输出:true

后续遍历,故最后一个节点一定是根节点,而中间一定从某一个位置分开,其左边全部为左子树,右边全部为右子树,只要判断左子树全部比根小,右子树比根大递归下去,看是否满足,如果找不到这个点,则返回false;

class Solution {
   
    int[] seq;
    public boolean verifySequenceOfBST(int [] sequence) {
   
        seq = sequence;
        return dfs(0,seq.length - 1);
    }
    public boolean dfs(int l, int r){
   
        if(l >= r)return true;
        int root = seq[r],k = 0;
        while(k < r && seq[k] < root)k++;// 都比根小的为左子树
        for(int i = k; i < r; i ++) // 右子树是不是都比根大,是的话继续,否则false;
            if(seq[i] < root)return false;
        return dfs(l,k - 1) && dfs(k,r - 1);
    }
}

二叉搜索树:故中序遍历为升序

可以利用中序遍历,和后序遍历,当两个遍历中左子树和右子树个数不同时,返回false;

class Solution {
   
    int[] seq1,seq2;// seq1--中序遍历,seq2 -- 后序遍历
    Map<Integer,Integer> map = new HashMap<>();
    public boolean verifySequenceOfBST(int [] sequence) {
   
        seq2 = sequence.clone();
        Arrays.sort(sequence);
        seq1 = sequence;
        for(int i = 0; i < seq1.length; i ++)
            map.put(seq1[i],i);
        return dfs(0,seq1.length - 1,0,seq1.length - 1);
    }
    public boolean dfs(int l1, int r1,int l2, int r2){
   
        if(r1 - l1 != r2 - l2)return false;
        if(l2 >= r2 || l1 >= r1)return true;
        int root = seq2[r2],k = map.get(root),i = 0;
        while(i < r2 && seq2[i] < root)i++;// 都比根小的为左子树
        return dfs(l1,k - 1,l2,i-1) && dfs(k+1,r1,i,r2 - 1);
    }
}

47. 二叉树中和为某一值的路径

输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。

从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

样例
给出二叉树如下所示,并给出num=22。
      5
     / \
    4   6
   /   / \
  12  13  6
 /  \    / \
9    1  5   1

输出:[[5,4,12,1],[5,6,6,5]]

没看见加粗字体,人都搞傻了。

就是先序遍历,求解即可

class Solution {
   
    List<List<Integer>> res = new ArrayList<>();
    int total;
    public List<List<Integer>> findPath(TreeNode root, int sum) {
   
        if(root == null)return res;
        total = sum;
        Integer[] temp = new Integer[10050];
        dfs(root,temp,root.val,1);
        return res;
    }
    public void dfs(TreeNode root,Integer[] temp,int t,int step){
   
        if(t > total)return ;
        temp[step] = root.val;
        if(root.left == null && root.right == null && t == total){
   
            List<Integer> tt = new ArrayList<>();
            for(int i = 1; i <= step; i ++)tt.add(temp[i]);
            res.add(tt);
        }
        if(root.left != null)dfs(root.left,temp,t+root.left.val,step + 1);
        if(root.right != null)dfs(root.right,temp,t+root.right.val,step + 1);
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值