算法作业_37(2017.6.19第十八周)

来源:互联网 发布:sublime json 格式化 编辑:程序博客网 时间:2024/06/05 12:44

104. Maximum Depth of Binary Tree

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.

Subscribe to see which companies asked this question.


111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Subscribe to see which companies asked this question.

解析:这是两道相似的二叉树递归问题,但是测试用例还是存在一些差别。如111最小的长度,如果一棵树只有一颗子树,那么最短长度不是0 也不是1,而是子数的最短长度。

Maximum Depth of Binary Tree

/** * 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;        int leftMax = maxDepth(root->left);        int rightMax = maxDepth(root->right);        return max( leftMax , rightMax) +1;    }};

Minimum Depth of Binary Tree

/** * 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 minDepth(TreeNode* root) {        if(root ==NULL) return 0 ;        int left = 0, right = 0 ;        if(root->left == NULL){            return  minDepth(root->right)+1;        }        if(root->right ==NULL){            return  minDepth(root->left)+1;        }else{            left = minDepth(root->left);            right = minDepth(root->right);        }        return min(left, right)+1;    }};




原创粉丝点击