Minimum Depth of Binary Tree

来源:互联网 发布:新余一中网络硬盘 编辑:程序博客网 时间:2024/06/05 10:50

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.

一开始题目没理解就开始编了,结果可想而知!注意:最小深度的意思是从根节点到最近叶节点的最短路径!是说遇到只有一个孩子的节点就返回。

所以递归的返回条件要分四种情况,第一种自然是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)return 0;//leaf nodeif (!root->left && !root->right)return 1;int i = minDepth(root->left);int j = minDepth(root->right);//one sideif (i==0 || j==0)return max(i,j) + 1;//two sidereturn min(i, j) + 1;    }};


0 0