力扣打卡 2021.11.17

二叉树属性问题:java

1.路径之和一:112 

此题只是简单判断是否具有这样的路径,所以判断一些特殊情况,如根节点为空时false,如无子孙节点时判断节点值是否等于判断的值,在排除后进行递归即可。

class Solution {

    public boolean hasPathSum(TreeNode root, int targetSum) {

        if (root == null) return false;

        if (root.left == null && root.right == null) return root.val == targetSum;

        return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val);

    }

}

2.路径之和二

看到遍历整棵树寻找可能的节点,首先想到深度遍历搜索dfs,找出所有可能的节点,建立一个栈来存储情况符合的节点。在dfs前,我们要确定一件事,是dfs的终止条件,那就是无子节点,且当前节点值等于targetsum。判断后,如满足则存入列表(将栈转为列表形式存入),否则继续深度搜索左右节点,并且最后一步删除来回溯。

class Solution {

    Deque<Integer> ans = new LinkedList<>();

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {

        dfs(root,targetSum);

        return res;

    }

    public void dfs (TreeNode root,int targetSum) {

        if (root == null) return;

        ans.offerLast(root.val);

        targetSum = targetSum - root.val;

        if (targetSum == 0 && root.left == null && root.right == null) {

            res.add(new LinkedList<>(ans));

        }

        dfs(root.left,targetSum);

        dfs(root.right,targetSum);

        ans.pollLast();

    }

}

3.二叉树展开为列表 114

看到题目前序遍历,首先想到的就是把二叉树通过前序遍历转换到列表中,然后通过列表里的节点遍历成一个链表。

class Solution {

    List<TreeNode> res = new ArrayList<>();

    public void flatten(TreeNode root) {

        preorder(root,res);

        for (int i = 1;i < res.size();i++) {

            TreeNode cur = res.get(i - 1), curnext = res.get(i);

            cur.right = curnext;

            cur.left = null;

        }

    }

    public void preorder(TreeNode root,List<TreeNode> res) {

        if (root == null) return;

        res.add(root);

        preorder(root.left,res);

        preorder(root.right,res);

    }

}

但是思考发现好像引用了数组,空间复杂度略高

4.求根节点到叶节点数字之和 129

看到题目求和,想到的深度遍历搜索建立dfs函数,因为此题有输出,所以返回值设置成int型,

我们需要确定dfs终止条件,是左右节点都为空时。最后递归即可

class Solution {

    public int sumNumbers(TreeNode root) {

        return dfs (root,0);

        

    }

    public int dfs(TreeNode root,int sum) {

        if (root == null) return 0;

        else {

            int sum2 = sum * 10 + root.val;

            if (root.left == null && root.right == null) return sum2;

            return dfs(root.left,sum2) + dfs(root.right,sum2);

        }

    } 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值