Day20_二叉树:Leetcode_110.平衡二叉树 + 257. 二叉树的所有路径 + 404.左叶子之和

LeetCode:110.平衡二叉树

问题描述

解决方案一:自底向下递归【类似于前序遍历的顺序】

1.思路

2.代码实现

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

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

3.复杂度分析

在这里插入图片描述

解决方案二:自底向上递归【类似于后序遍历的顺序】

1.思路

2.代码实现

class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        } else {
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}

3.复杂度分析

在这里插入图片描述

LeetCode:257. 二叉树的所有路径

问题描述

解决方案:

1.思路:

  • 使用深度优先搜索。在深度优先搜索遍历二叉树时,我们需要考虑当前的节点以及它的孩子节点。
  • 如果当前节点不是叶子节点,则在当前的路径末尾添加该节点,并继续递归遍历该节点的每一个孩子节点。
  • 如果当前节点是叶子节点,则在当前路径末尾添加该节点后我们就得到了一条从根节点到叶子节点的路径,将该路径加入到答案即可。

2.代码实现

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<String>();
        constructPaths(root, "", paths);
        return paths;
    }

    public void constructPaths(TreeNode root, String path, List<String> paths) {
        if (root != null) {
            StringBuffer pathSB = new StringBuffer(path);
            pathSB.append(Integer.toString(root.val));
            if (root.left == null && root.right == null) {  // 当前节点是叶子节点
                paths.add(pathSB.toString());  // 把路径加入到答案中
            } else {
                pathSB.append("->");  // 当前节点不是叶子节点,继续递归遍历
                constructPaths(root.left, pathSB.toString(), paths);
                constructPaths(root.right, pathSB.toString(), paths);
            }
        }
    }
}

3.复杂度分析

在这里插入图片描述

LeetCode:404.左叶子之和

问题描述

解决方案:

1.思路:

  • 递归逻辑是:如果左节点不为空,并且左节点的左右孩子为空,那么就符号条件,加入和即可;

2.代码实现

class Solution {
    int sum = 0;
    
public int sumOfLeftLeaves(TreeNode root) {
    help(root);
    return sum;
}

public void help(TreeNode root) {
    if (root == null) {
        return;
    }
    if (root.left != null && root.left.left == null && root.left.right == null) {
        sum += root.left.val;
    }
    help(root.left);
    help(root.right);
	}
}

3.复杂度分析

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值