104. Maximum Depth of Binary Tree

来源:互联网 发布:ip网络广播问题解决 编辑:程序博客网 时间:2024/05/17 01:50

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.

算法1:dfs递归求解

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxDepth(TreeNode *root) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if(root == NULL)return 0;        int res = INT_MIN;        dfs(root, 1, res);        return res;    }    void dfs(TreeNode *root, int depth, int &res)    {        if(root->left == NULL && root->right == NULL && res < depth)            {res = depth; return;}        if(root->left)            dfs(root->left, depth+1, res);        if(root->right)            dfs(root->right, depth+1, res);    }};

算法2:层序遍历,树的总层数就是树的最大高度

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxDepth(TreeNode *root) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        //层序遍历计算树的层数即可,NULL作为每一层节点的分割标志        if(root == NULL)return 0;        int res = 0;        queue<TreeNode*> Q;        Q.push(root);        Q.push(NULL);        while(Q.empty() == false)        {            TreeNode *p = Q.front();            Q.pop();            if(p != NULL)            {                if(p->left)Q.push(p->left);                if(p->right)Q.push(p->right);            }            else             {                res++;                if(Q.empty() == false)Q.push(NULL);            }        }        return res;    }};


0 0
原创粉丝点击