行业知识
代码随想录训练营Day17:● 110.平衡二叉树 ● 257. 二叉树的所有路径 ● 404.左叶子之和
2026-11-14 01:42:43
来源:互联网转载
110.平衡二叉树
题目链接
https://leetcode.cn/problems/balanced-binary-tree/description/
题目描述
思路
使用后序遍历,即左右中顺序
/** * 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 getdepth(root)!=-1; } public int getdepth(TreeNode root){ if(root==null) return 0; int leftdepth = getdepth(root.left); if(leftdepth==-1) return -1; int rightdepth = getdepth(root.right); if(rightdepth==-1) return -1; if(Math.abs(leftdepth-rightdepth)>1){ return -1; } return Math.max(leftdepth,rightdepth)+1; }} 257. 二叉树的所有路径
题目链接
https://leetcode.cn/problems/binary-tree-paths/description/
题目描述
思路
没太明白。。。。。
class Solution { /** * 递归法 */ public List binaryTreePaths(TreeNode root) { List res = new ArrayList();// 存最终的结果 if (root == null) { return res; } List paths = new ArrayList();// 作为结果中的路径 traversal(root, paths, res); return res; } private void traversal(TreeNode root, List paths, List res) { paths.add(root.val);// 前序遍历,中 // 遇到叶子结点 if (root.left == null && root.right == null) { // 输出 StringBuilder sb = new StringBuilder();// StringBuilder用来拼接字符串,速度更快 for (int i = 0; i "); } 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);// 回溯 } }} 404.左叶子之和
题目链接
https://leetcode.cn/problems/sum-of-left-leaves/description/
题目描述
思路
首先有几个误区说一下,1、左叶子节点,表示既是叶子节点同时也是左孩子
然后是思路,因为找一个叶子节点很好找,即他的左右孩子都为空即可,但是如何确定是左孩子就不整了,
所以本题思路为判断一个节点他的左孩子不为空,同时他的左孩子必须左右为空(即是叶子节点)
相对于递归而言,我还是更明白迭代方法,递归还得再理解理解
class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null) return 0; Stack stack = new Stack (); stack.add(root); int result = 0; while (!stack.isEmpty()) { TreeNode node = stack.pop(); 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; }}