LeetCode-111. Minimum Depth of Binary Tree

来源:互联网 发布:linux怎么退出man 编辑:程序博客网 时间:2024/05/17 23:41

问题:
https://leetcode.com/problems/minimum-depth-of-binary-tree/?tab=Description
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.
给定一个二叉树,找出它的最短深度。最短深度是指从节点到最近的叶节点的最短距离
分析:
分几种情况讨论。root为空,root左节点或者右节点为空,root左右节点都不为空。
参考C++代码:

/** * 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(root==NULL) return 0;        if(root->left==NULL)  return 1+minDepth(root->right);        if(root->right==NULL) return 1+minDepth(root->left);        int l=minDepth(root->left);        int r=minDepth(root->right);        return l<r?l+1:r+1;    }};
0 0
原创粉丝点击