classSolution{int ans;publicintmaxDepth(TreeNode root){
ans =0;dfs(root,0);return ans;}// 自顶向下publicvoiddfs(TreeNode node,int depth){// 需要先执行这句
ans =Math.max(ans, depth);if(node ==null)return;dfs(node.left, depth+1);dfs(node.right, depth+1);}}
LeetCode 226. 翻转二叉树
classSolution{publicTreeNodeinvertTree(TreeNode root){if(root ==null)returnnull;if(root.left ==null&& root.right ==null)return root;TreeNode left =invertTree(root.right);TreeNode right =invertTree(root.left);
root.left = left;
root.right = right;return root;}}
LeetCode 111. 二叉树的最小深度
classSolution{publicintminDepth(TreeNode root){if(root ==null)return0;if(root.left ==null&& root.right ==null)return1;int ans =Integer.MAX_VALUE;if(root.left !=null)
ans =Math.min(ans,minDepth(root.left));if(root.right !=null)
ans =Math.min(ans,minDepth(root.right));return ans+1;}}
classSolution{publicintsumOfLeftLeaves(TreeNode root){if(root ==null)return0;elsereturndfs(root);}publicintdfs(TreeNode node){int sum =0;if(node ==null)return sum;if(node.left !=null){if(isLeafNode(node.left)){
sum += node.left.val;}else
sum +=dfs(node.left);}if(node.right !=null&&!isLeafNode(node.right))
sum +=dfs(node.right);return sum;}publicbooleanisLeafNode(TreeNode node){return node.left ==null&& node.right ==null;}}
二叉树自底向上递归
自底向上(bottom-up)
和后序遍历紧密关联(左->右->根)
当前节点的情况依赖于其所有子节点的情况
考虑完所有子节点,再考虑当前节点
LeetCode 104. 二叉树的最大深度
classSolution{publicintmaxDepth(TreeNode root){returndfs(root);}// 自底向上publicintdfs(TreeNode node){if(node ==null)return0;int left =dfs(node.left);int right =dfs(node.right);returnMath.max(left,right)+1;}}