Leetcode: Minimum Depth of Binary Tree

来源:互联网 发布:机房还原软件 编辑:程序博客网 时间:2024/06/11 16:58

题目:
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.

思路分析:
求二叉树的最小深度。二叉树多用迭代。

C++示例代码:

/** * Definition for binary tree * 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;        }        //leftDepth=0,rightDepth=0直接返回1        if (root->left == NULL && root->right == NULL)        {            return 1;        }        int leftDepth = minDepth(root->left);        int rightDepth = minDepth(root->right);        //这里leftDepth和rightDepth不可能同时为0        if (leftDepth == 0)        {            return rightDepth + 1;        }        else if (rightDepth == 0)        {            return leftDepth + 1;        }        else        {            return min(leftDepth, rightDepth) + 1;        }    }};
0 0
原创粉丝点击