Minimum Depth of Binary Tree

来源:互联网 发布:僵直脊柱炎周杰伦知乎 编辑:程序博客网 时间:2024/06/06 17:05

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.

注意叶子节点的判断就可以

/** * 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) {        return subMinDepth(root,0);    }    int subMinDepth(TreeNode *node,int curDepth){        if(node==NULL){            return curDepth;        }        curDepth++;        int left=subMinDepth(node->left,curDepth);        int right=subMinDepth(node->right,curDepth);        if(node->left==NULL)            return right;            else if(node->right==NULL)            return left;        if(left>right)        return right;        else return left;            }};


0 0