Minimum Depth of Binary Tree 二叉树最小深度
来源:互联网 发布:商业摄影 知乎 编辑:程序博客网 时间:2024/05/29 07:37
//运用递归的思想,当节点为空时间,即1 2 V 3 V V V 。当左子树为空时,及左子树在具象图上面根本不存在,此时root的深度等于右子树的深度+1;反之亦然
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { return minRec(root); } private int minRec(TreeNode root) { if(root==null) return 0; int l = minRec(root.left); int r = minRec(root.right); if(l==0) return r+1; if(r==0) return l+1; return Math.min(l, r) + 1; } }
//也可以从另一方面想,就是当节点为空时间,判断右子树是否存在,当存在时,此节点深度为正无穷(INT_MAX);若不存在,则此节点深度为0
public class MinimumDepthofBinaryTree { public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; else { int leftDepth = root.left != null ? minDepth(root.left) : Integer.MAX_VALUE; int rightDepth = root.right != null ? minDepth(root.right) : Integer.MAX_VALUE; return Math.min(leftDepth,rightDepth) + 1; } }}
就比如说这样int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) { return 0; } else { minD(root); } } int minD(TreeNode *root) { if(root->left == NULL && root->right == NULL) { return 1; } else { if(root->left == NULL) { return minD(root->right) + 1; } else if(root->right == NULL) { return minD(root->left) + 1; } else { int left = minD(root->left); int right = minD(root->right); return (left<right?left:right) + 1; } } } };
0 0