111. Minimum Depth of Binary Tree

来源:互联网 发布:九章算法班 编辑:程序博客网 时间:2024/06/06 21:06

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. 当节点的左右孩子有一个非空时,递归到空的孩子节点时,要根据是否有兄弟节点来决定返回值。
2. 如果一味地将空节点返回0,就会导致[1, 2]这种二叉树的最小深度为1的情况(实际应该为2)。

/** * 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) {        return minDepth(root, false);    }    int minDepth(TreeNode *root, bool hasBrother) {        if (!root)            return hasBrother ? INT_MAX : 0;        return 1 + min(minDepth(root->left, root->right != NULL),                minDepth(root->right, root->left != NULL));    }};
0 0
原创粉丝点击