【二叉树】111. Minimum Depth of Binary Tree

来源:互联网 发布:云计算学习视频 编辑:程序博客网 时间:2024/05/17 23:04

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行是错的:

class Solution {public:    int minDepth(TreeNode* root) {        return root==NULL?0:1+min(minDepth(root->left),minDepth(root->right));    }};
这样写的错误在于,如果二叉树是斜的(也就是一个链表,没有左孩子或者右孩子),因为空的节点也参与了递归,那么min函数总是在这种地方取到

了0,这样的话返回的就只能是1了(也就是说最终只算了根节点。。。)

AC代码:

/** * 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) return 0;//递归用的边界,只有一个节点是1,下面的代码要+1,那么边界只能返回0        if(!root->left) return 1 + minDepth(root->right);//求右子树高度        if(!root->right) return 1 + minDepth(root->left);//求左子树高度        return 1+min(minDepth(root->left),minDepth(root->right));//根节点加上左子树/右子树中最小的高度的            }};





阅读全文
0 0
原创粉丝点击