zoukankan      html  css  js  c++  java
  • Maximum Depth of Binary Tree

    题目:Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    思路:深搜

    如果节点为空,返回0,;如果不为空,要看是否左右孩子节点是否存在,不存在直接返回1.

    然后剩下有说明至少存在一个,左节点在,就定义left加上1.右节点同样处理。


    代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     //本质上方法一样,只是通过实践竟然不同
    class Solution1 {
    //https://leetcode.com/problems/maximum-depth-of-binary-tree/
    public:
        int maxDepth(TreeNode* root) {
            if(root==NULL){
                return 0;
            }
            if(root->left==NULL&&root->right==NULL){
                return 1;
            }
    
            int left=0;
            if(root->left){
                left=maxDepth(root->left)+1;
            }
    
            int right=0;
            if(root->right){
                right=maxDepth(root->right)+1;
            }
    
            return max(left,right);
        }
    };
    
    class Solution2 {
    public:
        int count=1;
        int maxDepth(TreeNode* root) {
            if(root==NULL){
                return 0;
            }
            //int left=maxDepth(root->left);
            //int right=maxDepth(root->right);
            return max(maxDepth(root->left)+1,maxDepth(root->right)+1);
        }
    };


  • 相关阅读:
    5.3 员工管理系统之登录和过滤器
    5.2 员工管理系统之页面国际化
    5.1 员工管理系统之导入静态资源
    5.0 Thymeleaf表达式使用
    1.初识Hadoop
    左耳朵耗子谈直面焦虑和成长
    10.高性能JavaScript
    9.高可维护性的JavaScript
    springboot整合jsp踩坑
    springboot 上传图片与回显
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519882.html
Copyright © 2011-2022 走看看