算法训练营day17|110.平衡二叉树,257.二叉树的所有路径,404.左叶子之和

知识点

刷题

110.平衡二叉树

LeetCode链接 110. 平衡二叉树 - 力扣(LeetCode)

题目描述

方法1:dfs+递归

package daimasuixiangshuati.day16_erchashu;

/**
 * @Author LeiGe
 * @Date 2023/11/6
 * @Description todo
 */
public class PingHengErChaShu110_2 {
    /**
     * 概念:
     * 二叉树节点的深度:指从该节点到根节点的最长简单路径的边的条数
     * 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数
     * 题目中是通过判断高度差是否小于等于1来判断是不是平衡的
     * 求高度需要用后续遍历
     * <p>
     * 方法1:dfs,后序遍历,统计二叉树的高度
     * 0.-1表示树不平衡
     * 1.递归获取左子树的二叉树的高度
     * 2.递归获取右子树的二叉树的高度
     * 3.如果左子树不平衡,或者右子树不平衡,或者左右子树的高度差大于1,也不平衡,返回-1
     * 4.统计当前树的高度
     * 5.如果返回的不是-1,则是平衡的
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        return dfs(root) != -1;
    }

    private int dfs(TreeNode root) {
        //baseCase
        if (root == null) {
            return 0;
        }

        //获得左右子树高度
        int leftHeight = dfs(root.left);
        int rightHeight = dfs(root.right);

        //左右子树不平衡
        if (leftHeight == -1) {
            return -1;
        }
        if (rightHeight == -1) {
            return -1;
        }

        //左右子树高度差
        int diffHeight = Math.abs(leftHeight - rightHeight);

        //高度差大于1,不平衡,返回-1
        if (diffHeight > 1) {
            return -1;
        } else {
            //平衡,返回此树的高度
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }

    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;
        }
    }
}

方法2:迭代+栈

package daimasuixiangshuati.day16_erchashu;

import java.util.Stack;

/**
 * @Author LeiGe
 * @Date 2023/11/6
 * @Description todo
 */
public class PingHengErChaShu110_3 {
    /**
     * 方法2:栈+迭代
     * 我们可以使用层序遍历来求深度,但是就不能直接用层序遍历来求高度了,这就体现出求高度和求深度的不同。
     * 本题的迭代方式可以先定义一个函数,专门用来求高度。
     * 这个函数通过栈模拟的后序遍历找每一个节点的高度(其实是通过求传入节点为根节点的最大深度来求的高度)
     * <p>
     * 优化迭代法,针对暴力迭代法的getHeight方法做优化,利用TreeNode.val来保存当前结点的高度,这样就不会有重复遍历
     * 获取高度算法时间复杂度可以降到O(1),总的时间复杂度降为O(n)。
     * 用栈模拟后续遍历
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {

            // 中
            TreeNode node = stack.peek();
            stack.pop();

            // 判断左右孩子的高度是否符合
            if (Math.abs(getDepth(node.left) - getDepth(node.right)) > 1) {
                return false;
            }

            // 右
            if (node.right != null) {
                stack.push(node.right);
            }

            // 左
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return true;
    }

    /**
     * 后序遍历求节点高度,统一迭代法
     */
    public int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        // 记录深度
        int depth = 0;
        int result = 0;

        while (!stack.isEmpty()) {
            TreeNode peek = stack.peek();
            if (peek != null) {
                stack.pop();
                stack.push(peek);
                stack.push(null);
                depth++;
                if (peek.right != null) {
                    stack.push(peek.right);
                }
                if (peek.left != null) {
                    stack.push(peek.left);
                }
            } else {
                stack.pop();
                stack.pop();
                depth--;
            }
            result = Math.max(result, depth);
        }

        return result;
    }

    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;
        }
    }
}

257.二叉树的所有路径

LeetCode链接 257. 二叉树的所有路径 - 力扣(LeetCode)

题目描述

方法1:dfs+回溯

package daimasuixiangshuati.day17_erchashu;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author LeiGe
 * @Date 2023/11/7
 * @Description todo
 */
public class ErChaShuDeSuoYouLuJing257_1 {
    /**
     * 这道题目实际上是一道回溯算法的题
     * <p>
     * 方法1:dfs-递归-回溯
     * 1.叶子节点,将路径加入到结果中
     * 2.左子树递归回溯
     * 3.右子树递归回溯
     *
     * @param root
     * @return
     */
    public List<String> binaryTreePaths(TreeNode root) {
        // 存放最后的结果
        ArrayList<String> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        ArrayList<Integer> paths = new ArrayList<>();
        dfs(root, paths, result);
        return result;
    }

    private void dfs(TreeNode root, ArrayList<Integer> paths, ArrayList<String> result) {
        // 处理本节点
        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));
            result.add(sb.toString());
            return;
        }
        //左子树递归回溯
        if (root.left != null) {
            dfs(root.left, paths, result);
            paths.remove(paths.size() - 1);
        }
        //右子树递归回溯
        if (root.right != null) {
            dfs(root.right, paths, result);
            paths.remove(paths.size() - 1);
        }
    }

    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;
        }
    }
}

方法2:bfs+队列

队列,节点和路径成对出现,路径就是从根节点到当前节点的路径,相当于每次加入的路径都是简历在上一次的基础上加的

package daimasuixiangshuati.day17_erchashu;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author LeiGe
 * @Date 2023/11/7
 * @Description todo
 */
public class ErChaShuDeSuoYouLuJing257_2 {
    /**
     * 方法2:bfs-队列
     * 队列,节点和路径成对出现,路径就是从根节点到当前节点的路径
     * 相当于每次加入的路径都是简历在上一次的基础上加的
     *
     * @param root
     * @return
     */
    public List<String> binaryTreePaths(TreeNode root) {
        return bfs(root);
    }

    private List<String> bfs(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        //队列,节点和路径成对出现,路径就是从根节点到当前节点的路径
        Queue<Object> queue = new LinkedList<>();
        queue.add(root);
        queue.add(root.val + "");
        while (!queue.isEmpty()) {
            TreeNode node = (TreeNode) queue.poll();
            String path = (String) queue.poll();
            //如果到叶子节点,说明找到了一条完整路径
            if (node.left == null && node.right == null) {
                res.add(path);
            }

            //右子节点不为空就把右子节点和路径存放到队列中
            if (node.right != null) {
                queue.add(node.right);
                queue.add(path + "->" + node.right.val);
            }

            //左子节点不为空就把左子节点和路径存放到队列中
            if (node.left != null) {
                queue.add(node.left);
                queue.add(path + "->" + node.left.val);
            }
        }
        return res;
    }

    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;
        }
    }
}

方法3:dfs+栈

和方法2一样的思路,只不过一个是bfs,一个是dfs

package daimasuixiangshuati.day17_erchashu;

import java.util.*;

/**
 * @Author LeiGe
 * @Date 2023/11/7
 * @Description todo
 */
public class ErChaShuDeSuoYouLuJing257_3 {
    /**
     * 方法3:dfs+栈
     * 用栈实现前序遍历
     *
     * @param root
     * @return
     */
    public List<String> binaryTreePaths(TreeNode root) {
        return dfs(root);
    }

    private List<String> dfs(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<Object> stack = new Stack<>();
        stack.push(root);
        stack.push(root.val + "");
        while (!stack.isEmpty()) {
            // 节点和路径同时出栈
            String path = (String) stack.pop();
            TreeNode node = (TreeNode) stack.pop();

            // 如果找到叶子节点
            if (node.left == null && node.right == null) {
                res.add(path);
            }

            // 右子节点
            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }
            // 左子节点
            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
        }
        return res;
    }

    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;
        }
    }
}

404.左叶子之和

LeetCode链接 404. 左叶子之和 - 力扣(LeetCode)

题目描述

方法1:dfs+递归

package daimasuixiangshuati.day17_erchashu;

/**
 * @Author LeiGe
 * @Date 2023/11/8
 * @Description todo
 */
public class ZuoYeZiZhiHe404_1 {
    /**
     * 方法1:dfs+递归
     *
     * @param root
     * @return
     */
    public int sumOfLeftLeaves(TreeNode root) {
        return dfs1(root);
    }

    private int dfs1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return 0;
        }

        //左子树
        int leftValue = dfs1(root.left);
        //右子树
        int rightValue = dfs1(root.right);

        // 左子树就是一个左叶子的情况
        if (root.left != null && root.left.left == null && root.left.right == null) {
            //中
            leftValue = root.left.val;
        }
        return leftValue + rightValue;
    }

    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;
        }
    }
}

方法2:dfs+栈

package daimasuixiangshuati.day17_erchashu;

import java.util.Stack;

/**
 * @Author LeiGe
 * @Date 2023/11/8
 * @Description todo
 */
public class ZuoYeZiZhiHe404_2 {
    /**
     * 方法2:dfs+栈
     *
     * @param root
     * @return
     */
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        int result = 0;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();

            //如果node.left是左子节点,节点的值累加和
            if (node.left != null && node.left.left == null && node.left.right == null) {
                result += node.left.val;
            }
            if (node.right != null) {
                stack.add(node.right);
            }
            if (node.left != null) {
                stack.add(node.left);
            }
        }
        return result;
    }

    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;
        }
    }
}

方法3:bfs+队列

package daimasuixiangshuati.day17_erchashu;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @Author LeiGe
 * @Date 2023/11/8
 * @Description todo
 */
public class ZuoYeZiZhiHe404_3 {
    /**
     * 方法3:bfs+队列
     *
     * @param root
     * @return
     */
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();

                // 左子树
                if (node.left != null) {
                    // 如果是左叶子节点
                    if (isLeafNode(node.left)) {
                        ans += node.left.val;
                    } else {
                        queue.offer(node.left);
                    }
                }

                // 右子树
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return ans;
    }

    /**
     * 判断是否是左叶子节点
     *
     * @param node
     * @return
     */
    public boolean isLeafNode(TreeNode node) {
        return node.left == null && node.right == null;
    }

    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;
        }
    }
}

小结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值