美文网首页
leetcode112.路径总和,113.路径总和II

leetcode112.路径总和,113.路径总和II

作者: 憨憨二师兄 | 来源:发表于2020-05-19 15:14 被阅读0次

    路径总和

    题目链接

    思路:递归

    使用递归遍历整棵树

    代码如下:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null){
                return false;
            }
            if(root.left != null && root.right != null){
                return hasPathSum(root.left,sum - root.val) || hasPathSum(root.right,sum - root.val);
            } 
            else if(root.left != null){
                return hasPathSum(root.left,sum - root.val);
            }
            else if(root.right != null){
                return hasPathSum(root.right,sum - root.val);
            }
            else{
                return root.val == sum;
            }
        }
    }
    

    时间复杂度:遍历了二叉树的每个节点,时间复杂度为O(N)
    额外空间复杂度:当树非平衡二叉树,在极端的情况下,使用递归栈的空间为O(N),对平衡二叉树而言,递归深度为logN,所以额外空间复杂度为O(N)

    执行结果:


    路径总和II

    题目链接

    思路:递归+回溯

    代码如下:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
    
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<>();
            List<Integer> list = new ArrayList<>();
            process(root,sum,res,list);
            return res;
        }
    
        private void process(TreeNode root,int sum,List<List<Integer>> res,List<Integer> list){
            if(root == null){
                return;
            }
            list.add(root.val);
            if(root.left == null && root.right == null && sum == root.val){
                res.add(new ArrayList<>(list));
            }
            process(root.left,sum - root.val,res,list);
            process(root.right,sum - root.val,res,list);
            list.remove(list.size() - 1);
        }
    }
    

    时间复杂度:O(N)
    额外空间复杂度:递归栈最多消耗的额外空间为O(N)

    执行结果:


    相关文章

      网友评论

          本文标题:leetcode112.路径总和,113.路径总和II

          本文链接:https://www.haomeiwen.com/subject/wfjbohtx.html