DFS: 111. Minimum Depth of Binary Tree

来源:互联网 发布:android chroot linux 编辑:程序博客网 时间:2024/05/16 02:58

这个题一开始我是按照求最大深度算的,只是把max改成min,发现大错特错。例如[1, 2]这个树就通不过。所以这次不能一次只看一个结点,一次需要看两层。如果左右子树都是NULL的才是叶子节点,左右子树有一个不是NULL他就不是叶子节点。我的代码:

/** * 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 && root->right == NULL)            return 1;        else if(root->left != NULL && root->right != NULL)            return min(minDepth(root->left), minDepth(root->right)) + 1;        else if(root->left != NULL)            return minDepth(root->left) + 1;        else             return minDepth(root->right) + 1;                }   };
我这是把子树的所有情况全都写了一遍,肯定又写麻烦了,看看别人写的:

class Solution {public:    int minDepth(TreeNode *root) {        if(!root) return 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));    }};




原创粉丝点击