zoukankan      html  css  js  c++  java
  • leetcode 111 Minimum Depth of Binary Tree(DFS)

    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.

    题解:注意没有的分支不算。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int dfs(TreeNode *r){
            if(r==NULL) return 0;
            if(r->left==NULL&&r->right==NULL){
                return 1;
            }
            else{
                if(r->left==NULL){
                    return dfs(r->right)+1;
                }
                else if(r->right==NULL){
                    return dfs(r->left)+1;
                }
                else{
                    return min(dfs(r->left),dfs(r->right)) + 1;
                }
            }
        }
    
        int minDepth(TreeNode* root) {
            return dfs(root);
        }
    };
  • 相关阅读:
    Currency Exchange
    Robot Motion
    Crashing Robots
    Parencodings
    Y2K Accounting Bug
    Tautology
    Power of Cryptography
    Radar Installation -poj 1328
    The Pilots Brothers' refrigerator
    【java】之cron表达式
  • 原文地址:https://www.cnblogs.com/zywscq/p/5220977.html
Copyright © 2011-2022 走看看