LeetCode 111. Minimum Depth of Binary Tree

来源:互联网 发布:windows 高精度sleep 编辑:程序博客网 时间:2024/04/20 23:32

题目:
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,如果根节点只有左节点 ,返回 minDepth(root->left)+1;如果根节点只有右节点,返回minDepth(root->right)+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(NULL==root){//如果根节点为NULL,返回0            return 0;        }        else if(root->left==NULL&&root->right==NULL){//如果根节点没有叶节点,返回1            return 1;        }        else if(root->left!=NULL&&root->right==NULL){//如果根节点只有左节点            return minDepth(root->left)+1;        }        else if(root->left==NULL&&root->right!=NULL){//如果根节点只有右节点            return minDepth(root->right)+1;        }        else{//如果左右节点都有            return min(minDepth(root->left)+1,minDepth(root->right)+1);        }    }};

**输出结果:**9ms

0 0
原创粉丝点击