104. Maximum Depth of Binary Tree(DFS)

来源:互联网 发布:域名解析端口号 编辑:程序博客网 时间:2024/06/06 13:08

1. Description

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.


2. Analysis

问题转为求该二叉树的高度,只要计算出该二叉树有几层即可,是一道求二叉树高度的基础题,问题关键是保存遍历过的节点,从而遍历该些节点的子节点。用vector或queue皆可。难度系数:easy


3. Algorithm achievement

算法的时间复杂度为O(n).

/** * 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;        TreeNode * node = NULL;        int level = 0;        queue<TreeNode*> tmp;        tmp.push(root);        while( !tmp.empty()) {            level ++;            for(int i = 0, size = tmp.size(); i < size; i++) {                node = tmp.front();                tmp.pop();                if(node->left != NULL) {                    tmp.push(node->left);                }                if(node->right != NULL) {                    tmp.push(node->right);                }                       }           }        return level;       }};

原创粉丝点击