代码随想录算法训练营第17天 | 110、257、404

文章提供了三个关于二叉树问题的解决方案,包括判断平衡二叉树、获取二叉树所有路径以及计算左叶子之和。每个问题都通过递归或迭代方法进行了解决,强调了对二叉树遍历的理解和应用。

110.平衡二叉树

题目描述

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例1:
输入:root=[3,9,20,null,null,15,7]root = [3,9,20,null,null,15,7]root=[3,9,20,null,null,15,7]
输出:truetruetrue
示例2:
输入:root=[1,2,2,3,3,null,null,4,4]root = [1,2,2,3,3,null,null,4,4]root=[1,2,2,3,3,null,null,4,4]
输出:falsefalsefalse
示例1:
输入:root=[]root = []root=[]
输出:truetruetrue

思路

首先想到的会是递归法,通过构建一个递归函数来计算左右子树的高度然后作出判断即可。
能递归完成的方法当然也可以使用迭代但本题中会觉得没啥必要。

解法

/**
 * 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) {
        return height(root) != -1;
    }
    public int height(TreeNode root){
        if(root == null) return 0;
        int leftHeight = height(root.left);
        if(leftHeight == -1) return -1;
        int rightHeight = height(root.right);
        if(rightHeight == -1) return -1;
        if(Math.abs(leftHeight-rightHeight) > 1) return -1;
        return Math.max(leftHeight,rightHeight)+1;
    }
}

总结

简单题,直接写就完事了。

257.二叉树的所有路径

题目描述

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例1:
输入:root=[1,2,3,null,5]root = [1,2,3,null,5]root=[1,2,3,null,5]
输出:["1−>2−>5","1−>3"]["1->2->5","1->3"]["1>2>5","1>3"]
示例2:
输入:root=[1]root = [1]root=[1]
输出:["1"]["1"]["1"]

思路

具体实施起来没有那么好想,能看出要用递归,但具体实施过程很容易出错。而且其实迭代法感觉更好想到。

解法1

/**
 * 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 List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        List<Integer> paths = new ArrayList<>();
        traversal(root,paths,res);
        return res;
    }
    public void traversal(TreeNode root,List<Integer> paths,List<String> res){
        paths.add(root.val);
        if(root.left == null && root.right == null){
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<paths.size()-1;i++){
                sb.append(paths.get(i)).append("->");
            }
            sb.append(paths.get(paths.size()-1));
            res.add(sb.toString());
            return;
        }
        if(root.left != null){
            traversal(root.left,paths,res);
            paths.remove(paths.size()-1);
        }
        if(root.right != null){
            traversal(root.right,paths,res);
            paths.remove(paths.size()-1);
        }
    }
}

解法2

/**
 * 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 List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if(root == null) return result;
        Stack<TreeNode> stkTree = new Stack<>();
        Stack<String> stkPath = new Stack<>();
        stkTree.push(root);
        stkPath.push(root.val+"");
        while(!stkTree.isEmpty() && !stkPath.isEmpty()){
            String path = stkPath.pop();
            TreeNode node  = stkTree.pop();
            if(node.left == null && node.right == null){
                result.add(path);
            }
            if(node.right != null){
                stkTree.push(node.right);
                stkPath.push(path+"->"+node.right.val);
            }
            if(node.left != null){
                stkTree.push(node.left);
                stkPath.push(path+"->"+node.left.val);
            }
        }
        return result;
    }
}

总结

回头看能够发现其实就是在普通的二叉树遍历基础上进行了一些改动,但具体改动的位置和操作的细节仍然需要注意。

404.左叶子之和

题目描述

给定二叉树的根节点 root ,返回所有左叶子之和。
示例1:
输入:root=[3,9,20,null,null,15,7]root = [3,9,20,null,null,15,7]root=[3,9,20,null,null,15,7]
输出:242424
示例2:
输入:root=[1]root = [1]root=[1]
输出:000

思路

第一时间想到了层序遍历,然后简单地认为最左端的元素即为所求,然后就错了。
本题最重要的是能够想清楚一个节点可以作为左叶子节点的人设,即其判定条件。然后就是使用普通的遍历即可,只需将输出替换为判断。

解法1

/**
 * 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 sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        int leftValue = sumOfLeftLeaves(root.left);
        int rightValue = sumOfLeftLeaves(root.right);
        int minValue = 0;
        if(root.left != null && root.left.left == null && root.left.right == null){
            minValue = root.left.val;
        }
        int sum = minValue + leftValue + rightValue;
        return sum;
    }
}

解法2

/**
 * 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 sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        Stack<TreeNode> stk = new Stack<>();
        stk.add(root);
        int result = 0;
        while(!stk.isEmpty()){
            TreeNode node = stk.pop();
            if(node.left != null && node.left.left == null && node.left.right == null){
                result += node.left.val;
            }
            if(node.right != null) stk.add(node.right);
            if(node.left != null) stk.add(node.left);
        }
        return result;
    }
}

解法3

/**
 * 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 sumOfLeftLeaves(TreeNode root) {
        int sum = 0;
        if(root == null) return 0;
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        while(!que.isEmpty()){
            int size = que.size();
            while(size-- >0){
                TreeNode node = que.poll();
                if(node.left != null){
                    que.offer(node.left);
                    if(node.left.left == null && node.left.right == null){
                        sum += node.left.val;
                    }
                }
                if(node.right != null){
                    que.offer(node.right);
                }
            }
        }
        return sum;
    }
}

总结

最重要的是能够判断一个节点作为左叶子节点的判断条件。同时,其实做了这么多题会能够发现一大部分的二叉树问题都是在基础遍历的基础上进行改编。在做每一个二叉树问题时最好要先想想应该使用哪一个遍历方式,和使用何种改编方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值