二叉树的最大深度和最小深度实现

来源:互联网 发布:男神的偶像知乎 编辑:程序博客网 时间:2024/05/19 14:35

二叉树的最大深度

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
如果二叉树为空,则深度为0
如果不为空,分别求左子树的深度和右子树的深度,取最大的再加1.

二叉树的最小深度

给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
判断左子树或右子树是否为空,若左子树为空,则返回右子树的深度,反之返回左子树的深度,如果都不为空,则返回左子树和右子树深度的最小值。

代码实现:

#include <iostream>#include <vector>#include <list>using namespace std;class TreeNode{    public:        int val;        TreeNode *left, *right;        TreeNode(int m_val):val(m_val), left(NULL), right(NULL){        }        TreeNode* createTree(vector<int> list, int start); };TreeNode* TreeNode::createTree(vector<int> list, int start){        if(list[start] == '#')        {            return NULL;        }        TreeNode *root = new TreeNode(list[start]);        int lnode = 2*start + 1;        int rnode = 2*start + 2;        if(lnode > list.size() - 1)        {            root->left = NULL;        }        else        {            root->left = createTree(list, lnode);        }        if(rnode > list.size()- 1)        {            root->right = NULL;        }        else        {            root->right = createTree(list, rnode);        }        return root;}class Solution{    public:        int MinDepth(TreeNode *root){            if(root == NULL){                return 0;             }            if(root->left == NULL){                return MinDepth(root->right) + 1;            }            if(root->right == NULL){                return MinDepth(root->left) + 1;            }            int leftDepth = MinDepth(root->left) + 1;            int rightDepth = MinDepth(root->right) + 1;            return leftDepth < rightDepth ? leftDepth : rightDepth;        }        int MaxDepth(TreeNode *root){            if(root == NULL){                return 0;             }            int leftDepth = MaxDepth(root->left) + 1;            int rightDepth = MaxDepth(root->right) + 1;            return leftDepth > rightDepth ? leftDepth : rightDepth;        }};int main(){    Solution s;    vector<int> datanum;    datanum.push_back(1);    datanum.push_back(2);    datanum.push_back(3);    datanum.push_back(4);    datanum.push_back(5);    datanum.push_back('#');    datanum.push_back(6);    datanum.push_back('#');    datanum.push_back('#');    datanum.push_back(7);    datanum.push_back(8);    TreeNode *tree, *root;    root = tree->createTree(datanum, 0);    cout << s.MinDepth(root) << endl;    cout << s.MaxDepth(root) << endl;    system("pause");    return 0; } 
原创粉丝点击