104. Maximum Depth of Binary Tree 求树的最大深度

来源:互联网 发布:赫德森太太知乎 编辑:程序博客网 时间:2024/06/05 00:23

1,my solution

/** * 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 ans;    int maxDepth(TreeNode* root) {        help(root, 1);        return ans;        }    void help(TreeNode* root, int depht){        if(root == NULL) return;        ans = max(ans, depht);         help(root->left, depht + 1);        help(root->right, depht + 1);            }};

2,another solution

int maxDepth(TreeNode* root) {    if(root == NULL){        return 0;    }    int depth_left = maxDepth(root->left) + 1;    int depth_right = maxDepth(root->right) + 1;    return depth_left > depth_right ? depth_left : depth_right;}
  1. Depth-first-search
    ======

Only one line code.

int maxDepth(TreeNode *root){    return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;}
  1. Breadth-first-search
    ======

Calculate the count of the last level.

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;}

0 0
原创粉丝点击