12
05/2015
[LeetCode] Minimum Depth of Binary Tree
Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
解题思路:
这里的深度表示叶子节点到根节点的距离。比如[1, 2]的最小深度为2,而不是1。其代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if(root==NULL){ return 0; }else if(root->left==NULL&&root->right==NULL){ return 1; //表示root是叶子节点 }else if(root->left!=NULL&&root->right==NULL){ return 1 + minDepth(root->left); }else if(root->left==NULL&&root->right!=NULL){ return 1 + minDepth(root->right); }else{ return 1 + min(minDepth(root->left), minDepth(root->right)); } } };
二次刷题(2015-08-04)
这道题一定要弄清题意,这里的高度只根节点到叶子节点的路径长度。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if(root==NULL){ return 0; } if(root->left == NULL && root->right == NULL){ return 1; } if(root->left!=NULL && root->right ==NULL){ return 1 + minDepth(root->left); } if(root->left==NULL && root->right != NULL){ return 1 + minDepth(root->right); } return 1 + min(minDepth(root->left), minDepth(root->right)); } };
0 条评论