小白力扣算法题day08-树
对于递归遍历,先中后的代码很像,很简单。
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); inorder(root, result); return result; } private void inorder(TreeNode node, List<Integer> result) { if (node == null) { return; } inorder(node.left, result); result.add(node.val); inorder(node.right, result); } }层序遍历,利用队列的先进先出的特性去做。
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> currentLevel = new ArrayList<>(); int currentSize = queue.size(); for (int i = 0; i < currentSize; i++) { TreeNode node = queue.poll(); currentLevel.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } result.add(currentLevel); } return result; } }class Solution { public int maxDepth(TreeNode root) { if(root==null) return 0; int lh=maxDepth(root.left); int rh=maxDepth(root.right); return Math.max(lh,rh)+1; } }这题不难,递归的简单应用。
class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p==null&&q==null){ return true; } if(p==null||q==null){ return false; } return p.val==q.val&& isSameTree(p.left,q.left)&& isSameTree(p.right,q.right); } }同样递归解题
上题判断两树是否相同,这个判断两树是否镜像。
class Solution { public boolean isSymmetric(TreeNode root) { if(root==null) return true; return isMirror(root.left,root.right); } private boolean isMirror(TreeNode left, TreeNode right) { if(left==null&&right==null) return true; if(left==null||right==null) return false; return left.val==right.val &&isMirror(left.left,right.right) &&isMirror(left.right,right.left); } }今天的题大差不差,都是递归的应用。
