目录
前言
二叉树:
树 是一种经常用到的数据结构,用来模拟具有树状结构性质的数据集合。
树里的每一个节点有一个值和一个包含所有子节点的列表。从图的观点来看,树也可视为一个拥有N 个节点和N-1 条边的一个有向无环图。
二叉树是一种更为典型的树状结构。如它名字所描述的那样,二叉树是每个节点最多有两个子树的树结构,通常子树被称作“左子树”和“右子树”。
一、二叉树遍历
详见文章:二叉树的遍历
二、二叉树最大深度
1. 自顶向下的进行计算二叉树最大深度
从root根节点,一层一层的计算深度,可使用的即为前序遍历,只不过带有深度参数
private int answer;
private void maximum_depth(TreeNode root, int depth) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
answer = Math.max(answer, depth);
}
maximum_depth(root.left, depth + 1);
maximum_depth(root.right, depth + 1);
}
解题:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans = 0;
public int maxDepth(TreeNode root) {
if(root == null){
return ans;
}
maxD(root,1);
return ans;
}
public void maxD(TreeNode root,int depth){
if(root == null){
return;
}
if(root.left == null && root.right == null){
ans = Math.max(depth,ans);
return;
}
maxD(root.left,depth+1);
maxD(root.right,depth+1);
}
}
2.自底向上计算二叉树最大深度
自底向上” 是另一种递归方法。 在每个递归层次上,我们首先对所有子节点递归地调用函数,然后根据返回值和根节点本身的值得到答案。 这个过程可以看作是后序遍历的一种。
public int maximum_depth(TreeNode root) {
if (root == null) {
return 0; // return 0 for null node
}
int left_depth = maximum_depth(root.left);
int right_depth = maximum_depth(root.right);
return Math.max(left_depth, right_depth) + 1; // return depth of the subtree rooted at root
}
总结:
二叉树的最大深度即为通过二叉树遍历得到的,掌握好二叉树遍历是关键
每天进步一点点,加油!!!