LeetCode Week5 递归

这篇博客介绍了多种与二叉树相关的算法问题,包括计算二叉树的最大深度、最小深度、翻转二叉树、判断两棵树是否相同或对称,以及解决完全二叉树节点计数、平衡二叉树检测、路径总和、左叶子之和、所有路径和路径总和III等路径问题。同时,文章也探讨了二叉搜索树的性质,如最近公共祖先、验证二叉搜索树和删除节点的操作,并展示了如何从有序数组构建二叉搜索树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单递归(DFS)

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        
        invertTree(root.left);
        invertTree(root.right);
        
        return root;
    }   
}
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }

        return judge(root.left, root.right);
    }

    public boolean judge(TreeNode left, TreeNode right) {
        if (left == null || right == null) {
            return left == right;
        }

        if (left.val != right.val) {
            return false;
        }

        return judge(left.left, right.right) && judge(left.right, right.left);
    }
}
class Solution {
    public boolean isBalanced(TreeNode root) {
       if (root == null) {
            return true;
        }
        
        return (Math.abs(maxDepth(root.left) - maxDepth(root.right)) <=1) && isBalanced(root.left) && isBalanced(root.right);
    }

    int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }

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

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

路径问题(DFS)

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
         if (root == null) {
            return 0;
        }

        int res = 0;

        if (root.left != null && root.left.left == null && root.left.right == null) {
            res += root.left.val;
        }

        return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right) + res;
    }
}

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        combineStr(root, res, "");

        return res;
    }

    private void combineStr(TreeNode root, List<String> res, String str) {
        str += root.val;

        if (root.left == null && root.right == null) {
            res.add(str);
            return;
        }

        if (root.left != null) {
            combineStr(root.left, res, str+"->");
        }
        if (root.right != null) {
            combineStr(root.right, res, str+"->");

        }
    }
}
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return res;
        }

        calculate(root, new ArrayList<Integer>(), targetSum);

        return res;
    }

    private void calculate(TreeNode root, List<Integer> nums, int sum) {
        if (root == null) {
            return;
        }

        nums.add(root.val);
        if (root.left == null && root.right == null && root.val == sum) {
            res.add(new ArrayList<>(nums));
        }

        calculate(root.left, nums, sum - root.val);
        calculate(root.right, nums, sum - root.val);
            
        nums.remove(nums.size()-1);

    }
}
class Solution {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    public int dfs(TreeNode root, int prevSum) {
        if (root == null) {
            return 0;
        }
        int sum = prevSum * 10 + root.val;
        if (root.left == null && root.right == null) {
            return sum;
        } else {
            return dfs(root.left, sum) + dfs(root.right, sum);
        }
    }
}
class Solution {
    int sum = 0;

    public int pathSum(TreeNode root, int targetSum) {
        if(root==null) {
            return 0;
        }
        findPath(root, targetSum);
        pathSum(root.left, targetSum);
        pathSum(root.right, targetSum);
        return sum;
    }

    void findPath(TreeNode root, int target) {
        if (root == null) {
            return;
        }

        int diff = target - root.val;

        if (diff == 0) {
            sum++;
        }
        
        findPath(root.left, diff);
        findPath(root.right, diff);
        
    }
}

二叉搜索树(DFS)


class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode node, long lower, long upper) {
        if (node == null) {
            return true;
        }
        if (node.val <= lower || node.val >= upper) {
            return false;
        }
        return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
    }
}
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return root;
        }
        if (key < root.val) {
            TreeNode left = deleteNode(root.left, key);
            root.left = left;
        } else if (key > root.val) {
            TreeNode right = deleteNode(root.right, key);
            root.right = right;
        } else {
            TreeNode left = root.left;
            TreeNode right = root.right;
            //寻找右侧最小的叶子节点
            while (right != null && right.left != null) {
                right = right.left;
            }
            //如果存在右侧最小的叶子节点,将root的左子树拼接到右侧最小叶子节点的左子树
            if (right != null) {
                right.left = left;
                return root.right;
            } else {//如果不存在右侧最小的叶子节点,root的右子树为空,直接返回左子树
                return left;
            }
        }
        return root;
    }
}
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return buildBSTTree(nums, 0, nums.length - 1);
    }

    public TreeNode buildBSTTree(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }
        int middle = (start + end ) / 2;
        TreeNode root = new TreeNode(nums[middle]);
        root.left = buildBSTTree(nums, start, middle - 1);
        root.right = buildBSTTree(nums, middle + 1, end);
        return root;
    }
}
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        if (root == p || root == q) {
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if (left != null && right != null) {
            return root;
        } else if (left != null) {
            return left;
        } else if (right != null) {
            return right;
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值