二叉树的最大深度
如果二叉树不为空,则分别求二叉树的额左右子树的深度,然后取最大的的左树深度或右树深度,加1,因为根节点的深度是1
int maxDepth(TreeNode *root) { // write your code (here) if(root == NULL) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); }
求二叉树的最小深度和最大深度的区别
不能够直接将大于号改成小于号,会出现这样一种情况,当把小于号改成大于号时,当树是倾斜树时,即只有左子树或子右子树是,这样数的最小深度就会被求为1.
二叉树的最小深度是指从根节点到最小叶子的节点。
有两种实现方式:一种是判断左右子树是否为空,若左子树为空,则返回右子树的深度,若右子树为空,则返回左子树的深度,若左右子树都不为空,则返回左右子树的最小值。
一种是计算左右子树是判断是否等于0,如果等于0,深度赋值为最大值。
public int minDepth(TreeNode root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return 1; } if (root.left == null) { return minDepth(root.right) + 1; } if (root.right == null) { return minDepth(root.left) + 1; } int left = minDepth(root.left); int right = minDepth(root.right); return left < right ? (left + 1) : (right + 1); }
public int minDepth(TreeNode root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return 1; } int left = minDepth(root.left); if (left == 0) { left = Integer.MAX_VALUE; } int right = minDepth(root.right); if (root.right == null) { right = Integer.MAX_VALUE; } return left < right ? (left + 1) : (right + 1); }