7
Leetcode Minimum Depth of Binary Tree (面试题推荐)
source link: https://zxs.io/article/24
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Leetcode Minimum Depth of Binary Tree (面试题推荐)
我其他leetcode结题代码见我github https://github.com/xindoo/leetcode
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。
我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
/** * 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 = 0; int minDepth(TreeNode *root) { if (NULL == root) return 0; else mindepth = 0x3f3f3f3f; dfs(root, 1); return mindepth; } void dfs(TreeNode *root, int depth) { if (NULL != root->left) dfs(root->left, depth+1); if (NULL != root->right) dfs(root->right, depth+1); if (NULL == root->left && NULL == root->right) mindepth = min(mindepth, depth); } };
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK