LeetCode 104. Maximum Depth of Binary Tree

來源:互聯網
上載者:User

標籤:root   入隊   public   方法   非遞迴   null   gray   最大   ber   

Problem:

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.

初看本題第一印象為遞迴寫法。首先找出終止條件:node == NULL。若未進入遞迴終止狀態,則分左子樹和又子樹進行遞迴,最終返回累加最大的值。其代碼如下:

/** * 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 maxDepth(TreeNode* root)     {        if(root == NULL)        {            return 0;        }        int left_node = maxDepth(root->left) + 1;        int right_node = maxDepth(root->right) + 1;        return (left_node > right_node)? left_node : right_node;    }};

通過參看部落格發現,還有非遞迴解法——通過BFS求解。將一層的節點加入到一個隊列中,然後依次出隊。每一層入隊計數器加1,最後一層加入後即可算出總的深度。參見原博:http://blog.csdn.net/wangyaninglm/article/details/45700837

其代碼如下:

方法一:

int maxDepth(TreeNode *root){    if(root == NULL)        return 0;    int res = 0;    queue<TreeNode *> q;    q.push(root);    while(!q.empty())    {        res++;        for(int i = 0, n = q.size(); i < n; ++ i)        {            TreeNode *p = q.front();            q.pop();            if(p -> left != NULL)                q.push(p -> left);            if(p -> right != NULL)                q.push(p -> right);        }    }    return res;}

方法二:

int maxDepth(TreeNode *root){    if (root == NULL) return 0;    stack<TreeNode *> gray;    stack<int> depth;    int out = 0;    gray.push(root);    depth.push(1);    while (!gray.empty()) {        TreeNode *tmp = gray.top();        int num = depth.top();        gray.pop();        depth.pop();        if (tmp->left == NULL && tmp->right == NULL) {            out = num > out ? num : out;        }        else {            if (tmp->left != NULL) {                gray.push(tmp->left);                depth.push(num + 1);            }            if (tmp->right != NULL) {                gray.push(tmp->right);                depth.push(num + 1);            }        }    }    return out;}

 

LeetCode 104. Maximum Depth of Binary Tree

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.