• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
fangleSea
博客园    首页    新随笔    联系   管理    订阅  订阅
代码随想录day16| 二叉树(四)

110.平衡二叉树

递归法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        int arg = research(root);
        if (arg == -1) return false;
        return true;
    }
    public int research(TreeNode root){
        if(root == null) return 0;
        int right = research(root.right);
        if (right == -1) return -1;
        int left = research(root.left);
        if(left == -1) return -1;
        if(Math.abs(left - right) > 1) return -1;
        return Math.max(left, right) + 1;
    }
}

257. 二叉树的所有路径

本文我们开始初步涉及到了回溯,很多同学过了这道题目,可能都不知道自己其实使用了回溯,回溯和递归都是相伴相生的。

我在第一版递归代码中,把递归与回溯的细节都充分的展现了出来,大家可以自己感受一下。

第二版递归代码对于初学者其实非常不友好,代码看上去简单,但是隐藏细节于无形。

最后我依然给出了迭代法。

对于本题充分了解递归与回溯的过程之后,有精力的同学可以再去实现迭代法。

class Solution {
    public List<String> ans = new ArrayList<String>();
    public List<String> binaryTreePaths(TreeNode root) {
        search(root, "");
        return ans;
    }
    public void search(TreeNode node, String str){
        str += node.val;
        if (node.right == null && node.left == null){
            ans.add(str);
            return;
        }
        if(node.right != null) search(node.right, str+"->");
        if(node.left != null) search(node.left, str+"->");
        return;
    }
}

404.左叶子之和

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int ans = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        search(root);
        return ans;
    }
    public void search(TreeNode node){
        if (node == null) return;
        if(node.left != null && node.left.left == null && node.left.right == null) ans += node.left.val;
        if (node.left != null) search(node.left);
        if (node.right != null) search(node.right);
        return ;
    }
}

 

posted on 2023-06-05 00:12  跪求个offer  阅读(13)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3