110.平衡二叉树 (优先掌握递归)
再一次涉及到,什么是高度,什么是深度,可以巩固一下。
文章讲解/视频讲解:代码随想录
题目链接:
public boolean isBalanced(TreeNode root) { if(isbal(root)){ return true; }else{ return false; } } public boolean isbal(TreeNode root){ if(root == null){ return true; } if(Math.abs(isHigh(root.left)-isHigh(root.right))>1){ return false; }else{ return isbal(root.left) && isbal(root.right); } } public int isHigh(TreeNode root){ if(root == null){ return 0; } return Math.max(isHigh(root.left),isHigh(root.right))+1; }
257. 二叉树的所有路径 (优先掌握递归)
这是大家第一次接触到回溯的过程, 我在视频里重点讲解了 本题为什么要有回溯,已经回溯的过程。
如果对回溯 似懂非懂,没关系, 可以先有个印象。
文章讲解/视频讲解:代码随想录
题目链接:List<String> result = new ArrayList<>(); public List<String> binaryTreePaths(TreeNode root) { deal(root, ""); return result; } public void deal(TreeNode node, String s) { if (node == null) return; if (node.left == null && node.right == null) { result.add(new StringBuilder(s).append(node.val).toString()); return; } String tmp = new StringBuilder(s).append(node.val).append("->").toString(); deal(node.left, tmp); deal(node.right, tmp); }
404.左叶子之和 (优先掌握递归)
其实本题有点文字游戏,搞清楚什么是左叶子,剩下的就是二叉树的基本操作。
文章讲解/视频讲解:代码随想录
题目链接:
int result; public int sumOfLeftLeaves(TreeNode root) { sum(root); return result; } public void sum(TreeNode root){ if(root == null){ return; } if(root.left != null ){ if(root.left.left == null && root.left.right == null){ result += root.left.val; } } sum(root.right); sum(root.left); }