博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode: Minimum Depth of Binary Tree
阅读量:4621 次
发布时间:2019-06-09

本文共 1750 字,大约阅读时间需要 5 分钟。

简单题,少数次过

1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     int dfs(TreeNode *root, int dep) {13         if (!root) return dep;14         if (root->left && root->right) return min(dfs(root->left, dep+1), dfs(root->right, dep+1));15         if (!root->left && root->right) return dfs(root->right, dep+1);16         if (root->left && !root->right) return dfs(root->left, dep+1);17         if (!root->left && !root->right) return dep+1;18     }19     int minDepth(TreeNode *root) {20         // Start typing your C/C++ solution below21         // DO NOT write int main() function22         return dfs(root, 0);23     }24 };

 C#, 没有return 0会有编译错误,C#的要求比C++的严格,但是功能又不全。。太废。。

1 /** 2  * Definition for a binary tree node. 3  * public class TreeNode { 4  *     public int val; 5  *     public TreeNode left; 6  *     public TreeNode right; 7  *     public TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public int MinDepth(TreeNode root) {12         return dfs(root, 0);13     }14     public int dfs(TreeNode root, int dep) {15         if (root == null) return dep;16         if (root.left != null && root.right != null) return Math.Min(dfs(root.left, dep+1), dfs(root.right, dep+1));17         if (root.left == null && root.right != null) return dfs(root.right, dep+1);18         if (root.left != null && root.right == null) return dfs(root.left, dep+1);19         if (root.left == null && root.right == null) return dep + 1;20         return 0;21     }22 }
View Code

 

转载于:https://www.cnblogs.com/yingzhongwen/archive/2013/04/09/3010630.html

你可能感兴趣的文章
mysql CREATE USER
查看>>
H3C 快速以太网和千兆以太网
查看>>
oracle触发器——ddl触发器
查看>>
oracle函数 SOUNDEX(c1)
查看>>
spring-data-elasticsearch使用出现的一些小问题
查看>>
雷云Razer Synapse2.0使用测评 -第二次作业
查看>>
Android ProgressBar手动控制开始和停止
查看>>
【iCore3 双核心板】DEMO 1.0 测试程序发布
查看>>
LeetCode 112. Path Sum (二叉树路径之和)
查看>>
Author Agreement
查看>>
CSS实现三列布局
查看>>
ibatis (六) dynamic的用法
查看>>
windows和linux文件的转换
查看>>
找出linux服务器IO占用高的程序
查看>>
E-PUCK机器人-串口通信和I2C通信
查看>>
bzoj 1207
查看>>
.NET Core TDD 前传: 编写易于测试的代码 -- 依赖项
查看>>
2:Program.cs文件分析
查看>>
并查集并查集并查集
查看>>
[HTML,CSS]div+css垂直水平居中
查看>>