力扣二叉树简单题整理--(包含常用语法的讲解)

94 二叉树的中序遍历


java 复制代码
/**
 * 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<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        inorder(root,result);
        return result;
    }
    public void inorder(TreeNode node,List<Integer> result)
    {
        if(node==null)
        {
            return;
        }
        inorder(node.left,result);
        result.add(node.val);
        inorder(node.right,result);
    }
}

104 二叉树的最大深度

java 复制代码
class Solution {
    public int maxDepth(TreeNode root) {
        if(root ==null){return 0;}
       int left= maxDepth(root.left);
       int right =maxDepth(root.right);

      return 1+ Math.max(left,right);
    }
}

3.翻转二叉树


java 复制代码
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null ){return null;}

        TreeNode left=invertTree(root.left);
        TreeNode right=invertTree(root.right);

        root.left=right;
        root.right=left;
        return root;
    }
}
相关推荐
文丑颜不良啊42 分钟前
LeetCode3101~3120题目解析
java·leetcode
kyle~4 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯5 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好6 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘7 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程8 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊8 小时前
LeetCode3061~3080题目解析
java·leetcode
电科_银尘11 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习
文丑颜不良啊11 小时前
LeetCode3081~3100题目解析
java·leetcode
电科_银尘11 小时前
【大模型算法与工程 05】分类、回归与排序指标:怎样评价一个模型
算法·分类·回归