【题目】
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
【思路】
DFS(深搜优先搜索)或者BFS(广度优先搜索)都行。
【代码】
- Java
DFS:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private int maxDepth = 0;
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
getMaxDepth(root, 0);
return maxDepth;
}
void getMaxDepth(TreeNode root, int depth) {
if(root == null){
maxDepth = maxDepth > depth ? maxDepth : depth;
return;
}
getMaxDepth(root.left, depth + 1);
getMaxDepth(root.right, depth + 1);
}
}
DFS简洁版:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left > right ? left + 1 : right + 1;
}
}
BFS:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> que = new LinkedList<>();
int depth = 0;
que.add(root);
while (!que.isEmpty()) {
depth++;
int length = que.size();
for (int i = 0; i < length; i++) {
TreeNode node = que.poll();
if (node.left != null) que.add(node.left);
if (node.right != null) que.add(node.right);
}
}
return depth;
}
}