题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
常规dfs。
Code
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
int left = 1+TreeDepth(pRoot->left);
int right = 1+TreeDepth(pRoot->right);
return left > right ? left : right;
}
};
- java
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private int depth = 0;
void dfs(TreeNode root, int currentDepth) {
if(root == null) return ;
else if(root.left == null && root.right == null) {
depth = Math.max(depth, currentDepth);
} else {
dfs(root.left, currentDepth+1);
dfs(root.right, currentDepth+1);
}
}
public int TreeDepth(TreeNode root) {
dfs(root, 1);
return depth;
}
}