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
  • 相关阅读:
    aria2安装webui
    c++指针参数是如何传递内存的
    ssl 证书申请
    LNMP一键包安装后解决MySQL无法远程连接问题
    流水线设计 转:http://www.opengpu.org/forum.php?mod=viewthread&tid=2424
    IUS nc simulator
    ccd与coms摄像头的区别
    昨天下午写的FPGA驱动VGA显示图片
    tcl脚本
    用FPGA驱动ov7670摄像头用tft9328显示
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3010630.html
Copyright © 2011-2022 走看看