代码随想录训练营第十六天 | 二叉树
今天是第十六天,继续二叉树方面的递归练习
class Solution { public int maxDepth(TreeNode root) { if(root == null){ return 0; } else{ return Math.max(maxDepth(root.right), maxDepth(root.left))+1; } } }
这道题一直递归直到触碰到叶子。
class Solution { public int minDepth(TreeNode root) { if(root == null){ return 0; } if(root.left == null && root.right!=null){ return minDepth(root.right)+1; } if(root.left != null && root.right== null){ return minDepth(root.left)+1; } return Math.min(minDepth(root.left), minDepth(root.right))+1; } }
和上一道题的思路一样,只是要确定如果一棵树只有一颗子树为空的话,要顺着不为空的那颗子树往下递归。
class Solution { public int countNodes(TreeNode root) { if(root==null){ return 0; } return 1+ countNodes(root.left) + countNodes(root.right); } }
这题和前两题一样,为啥是medium
今天的都是二叉树简单的递归应用,明天的难度就上来了

浙公网安备 33010602011771号