- Maximum Depth of Binary Tree
- 一道简单的题目,要点有两个:(1)借助递归函数参量; (2)变量的初始化放在局部,在外部初始化提交的时候会报错,也就是不同case之间的height不独立了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int height;//变量尽可能在局部初始化
void helper(struct TreeNode* root, int depth){
if(root==NULL)
return;
if(height<depth)
height=depth;
helper(root->left,depth+1);
helper(root->right,depth+1);
}
int maxDepth(struct TreeNode* root) {
height=0;
helper(root,1);
return height;
}
- Java版本
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int height;
public void helper(TreeNode root, int depth){
if(root==null)return;
if(height<depth)height=depth;
helper(root.left,depth+1);
helper(root.right,depth+1);
}
public int maxDepth(TreeNode root) {
height=0;
helper(root,1);
return height;
}
}
- leet0111. Minimum Depth of Binary Tree
Runtime: 764 ms, faster than 5.34% of C online submissions for Minimum Depth of Binary Tree.
Memory Usage: 19.1 MB, less than 8.70% of C online submissions for Minimum Depth of Binary Tree.
二叉树的最小深度就是就最短路径的节点个数,用深度优先搜索DFS来完成。首先判空,若当前结点不存在,直接返回0。然后看若左子结点不存在,那么对右子结点调用递归函数,并加1返回。反之,若右子结点不存在,那么对左子结点调用递归函数,并加1返回。若左右子结点都存在,则分别对左右子结点调用递归函数,将二者中的较小值加1返回即可
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define min(a,b) (((a)<(b))?(a):(b))
int minDepth(struct TreeNode* root) {
if(root==NULL)return 0;
if(root->left==NULL)return 1+minDepth(root->right);
if(root->right==NULL)return 1+minDepth(root->left);
return 1+min(minDepth(root->left),minDepth(root->right));
}
*我们也可以是迭代来做,层序遍历,记录遍历的层数,一旦我们遍历到第一个叶结点,就将当前层数返回,即为二叉树的最小深度. C++ 代码如下:
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
int res = 0;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
++res;
for (int i = q.size(); i > 0; --i) {
auto t = q.front(); q.pop();
if (!t->left && !t->right) return res;
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
return -1;
}
};
- Java基础班给出的答案
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return getMin(root);
}
public int getMin(TreeNode root){
if (root == null) {
return Integer.MAX_VALUE;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.min(getMin(root.left), getMin(root.right)) + 1;
}
}
网友评论