标签:down res stream 递归 ota des 节点 span pat
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.
因此能够将每一个结点的左右两个子树的深度返回给父节点,父节点选择比較小的深度,然后再返回给祖先结点,以此类推,最后返回给根结点,得到终于结果。
#include <iostream> /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ 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; } int Result = 1; int Left = minDepth(root->left); int Right = minDepth(root->right); if (Left * Right) { Result += Left > Right?Right : Left; } else { Result += Right + Left; } return Result; } };
LeetCode_Minimum Depth of Binary Tree
标签:down res stream 递归 ota des 节点 span pat
原文地址:http://www.cnblogs.com/liguangsunls/p/6773832.html