zoukankan      html  css  js  c++  java
  • Leetcode 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.

    递归求解

    int maxDepth(TreeNode *root){
        return root? 1+max(maxDepth(root->left), maxDepth(root->right)) : 0;
    }

     非递归求解

    struct Node{
        TreeNode *node;
        int depth;
        Node(TreeNode *a = NULL , int d = 0):node(a), depth(d);
    };
    
    int maxDepth1(TreeNode *root){
        if(root == NULL) return 0;
        queue<Node> que;
        Node  rootNode(root,1);
        que.push(rootNode);
        int res = 0;
        while(!que.empty()){
            Node p = que.front();que.pop();
            res = p.depth;
            if(p.node->left)    que.push(Node(p.node->left,p.depth+1));
            if(p.node->right )  que.push(Node(p.node->right,p.depth+1));
        }
        return res;
    }
  • 相关阅读:
    作业3
    字符串的应用
    java类与对象
    作业
    水仙花数
    java例
    读书笔记(构建之法-11.19)
    补psp进度(11月4号-9号)
    PSP进度(11~16)
    团队项目-约跑软件需求规格说明书
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3803243.html
Copyright © 2011-2022 走看看