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.
Tree Depth-first Search
最小深度的意思是从根节点到最近叶节点的最短路径!不是说遇到只有一个孩子的节点就返回。
所以递归的返回条件要分四种情况,第一种自然是NULL节点,直接return 0;第二种是叶节点,return 1;第三种是有一个孩子的节点,返回的是有孩子那边的深度;最后时有两个孩子,返回的是小的深度。
所以递归的返回条件要分四种情况,第一种自然是NULL节点,直接return 0;第二种是叶节点,return 1;第三种是有一个孩子的节点,返回的是有孩子那边的深度;最后时有两个孩子,返回的是小的深度。
/** * Definition for binary tree * 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==NULL) return 1; int i=minDepth(root->left); int j=minDepth(root->right); if(i==0 || j==0) return max(i,j)+1; return min(i,j)+1; } };