Minimum Depth of Binary Tree

来源:互联网 发布:Java string转化为int 编辑:程序博客网 时间:2024/06/06 04:37

题目: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.

实例代码如下:

class Solution {public:int minDepth(TreeNode *root) {if(root==NULL)return 0;else{int mindepth=INT_MAX;vector<TreeNode*> treeNodeVec;minDepthFunc(root,mindepth,treeNodeVec);return mindepth;}}void minDepthFunc(TreeNode* root,int &mindepth,vector<TreeNode*> &treeNodeVec){if(root!=NULL){//首先访问根节点,加入vectreeNodeVec.push_back(root);//判断是否到达根节点if(root->left==NULL && root->right==NULL){if(treeNodeVec.size()<mindepth)mindepth=treeNodeVec.size();treeNodeVec.pop_back();//叶节点回溯return; //返回到上一层}if(root->left!=NULL)minDepthFunc(root->left,mindepth,treeNodeVec);if(root->right!=NULL)minDepthFunc(root->right,mindepth,treeNodeVec);treeNodeVec.pop_back();//非叶节点回溯}}};


0 0
原创粉丝点击