leetcode 之 Maximum Depth of Binary Tree

来源:互联网 发布:java jdbc 批量insert 编辑:程序博客网 时间:2024/05/21 09:54
问题:
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.

方法一. 广度优先遍历, 利用队列,在每一层的结尾插入一个标志表示该层结束。
#include <queue>#include <limits>using namespace std;/*** 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) {        if(root == NULL)            return 0;        queue<TreeNode *> tree_queue;        tree_queue.push(root);        TreeNode levelNode(std::numeric_limits<int>::max());        int max_depth = 0;        while( !tree_queue.empty() ){            tree_queue.push(&levelNode);            TreeNode * top = tree_queue.front();            tree_queue.pop();            //add all the children            while(top->val != std::numeric_limits<int>::max())            {                if(top->left){                    tree_queue.push(top->left);                }                if(top->right){                    tree_queue.push(top->right);                }                top = tree_queue.front();                tree_queue.pop();            }            //add depth when traverse one level            max_depth ++;        }        return max_depth;    }};


方法二 . 深度优先遍历,利用栈进行回溯。在每一层的结尾插入一个标志表示该层结束。在回溯时,一旦遇到标志位,减少当前的深度。
#include <stack>#include <limits>/*** 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) {        if(root == NULL)            return 0;        int max_depth = 0;        std::stack<TreeNode *> tree_stack;        tree_stack.push(root);        TreeNode *current = NULL;        TreeNode level(std::numeric_limits<int>::max());        int current_depth = 0;        while(!tree_stack.empty())        {            //pop top node.            current = tree_stack.top();            tree_stack.pop();            //visit level node.            if(current->val == std::numeric_limits<int>::max()){                current_depth --;            }            //insert new node.            else{                //insert a level flag.                tree_stack.push(&level);                current_depth ++;                if(max_depth < current_depth)                     max_depth = current_depth;                if(current->right)                    tree_stack.push(current->right);                if(current->left)                    tree_stack.push(current->left);            }        }        return max_depth;    }};



0 0
原创粉丝点击