zoukankan      html  css  js  c++  java
  • LeetCode: Minimum Depth of Binary Tree

    简单题,少数次过

     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 below
    21         // DO NOT write int main() function
    22         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
  • 相关阅读:
    checkbox radio select 选中总结
    vue-cli3总结
    数组总结
    Object 总结
    ajax总结
    canvas
    移动端事件
    微服务架构 SpringBoot(一)
    spring+activemq实战之配置监听多队列实现不同队列消息消费
    Integer 数值比较
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3010630.html
Copyright © 2011-2022 走看看