LeetCode【二叉树】

本文深入探讨LeetCode中关于二叉树的算法挑战,包括遍历、搜索、构造等各种操作。通过实例解析,帮助读者掌握二叉树的基本操作和常用解题策略。
摘要由CSDN通过智能技术生成

LinkedList<Integer> list = new LinkedList<>();
     public List<Integer> inorderTraversal(TreeNode root) {
         traverse(root);
         return list;
     }
     private void traverse(TreeNode root) {
         if (root == null){
             return;
         }
         traverse(root.left);
         list.add(root.val);
         traverse(root.right);
     }

 

public List<TreeNode> generateTrees(int n) {
         if (n == 0){
             return new LinkedList<>();
         }
         return build(1,n);
     }
     private List<TreeNode> build(int lo, int hi) {
         List<TreeNode> list = new LinkedList<>();
         if (lo > hi){
             list.add(null);
             return list;
         }
         //穷尽root节点所有可能节点
         for (int i = lo; i <= hi; i++){
             List<TreeNode> leftTree = build(lo,i-1);
             List<TreeNode> rightTree = build(i+1,hi);
             for (TreeNode left : leftTree){
                 for (TreeNode right : rightTree){
                     TreeNode root = new TreeNode(i);
                     root.left = left;
                     root.right = right;
                     list.add(root);
                 }
             }
         }
         return list;
     }

 int[][] memo;
     int numTrees(int n){
         memo = new int[n+1][n+1];
         return count(1,n);
     }

     private int count(int lo, int hi) {
         if (lo > hi){
             return 1;
         }
         if (memo[lo][hi] != 0){
             return memo[lo][hi];
         }
         
         int res = 0;
         for (int i = lo; i <= hi; i++){
             int left = count(lo,i-1);
             int right = count(i+1,hi);
             res += left*right;
         }
         memo[lo][hi] = res;
         return res;
     }

 public boolean isValidBST(TreeNode root) {
         return isValidBST(root, null, null);
     }

     /* 限定以 root 为根的子树节点必须满足 max.val > root.val > min.val */
     boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {
         if (root == null){
             return true;
         }
         if (min != null && root.val <= min.val){
             return false;
         }
         if (max != null && root.val >= max.val){
             return false;
         }
         return isValidBST(root.left,min,root) && isValidBST(root.right,root,max);
     }

 public boolean isSameTree(TreeNode p, TreeNode q) {

         if (p == null && q != null || p != null && q == null){
             return false;
         }
         if (p == null && q == null){
             return true;
         }
         
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-孤单又灿烂的神-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值