Minimum Depth of Binary Tree

来源:互联网 发布:nba直播数据统计 编辑:程序博客网 时间:2024/05/18 01:49

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.

Subscribe to see which companies asked this question

一种就是计算左子树和右子树深度的时候,判断是否等于0,如果等于0,说明该子树不存在,深度赋值为最大值。

第二种就是判断左子树或右子树是否为空,若左子树为空,则返回右子树的深度,反之返回左子树的深度,如果都不为空,则返回左子树和右子树深度的最小值

任何一个节点的深度  都得加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 (root == NULL)            return 0;                    if (root->left == NULL && root->right == NULL)            return 1;                    int leftDepth = minDepth(root->left);        int rightDepth = minDepth(root->right);        //判断一个节点是不是单支的如果是则该节点深度由他的一支决定,如果左为空,什么由右支决定        if (leftDepth == 0)            return rightDepth + 1;        else if (rightDepth == 0)            return leftDepth + 1;        else            return min(leftDepth, rightDepth) + 1;    }};



0 0
原创粉丝点击