算法模板
各类算法基础模板
三、二叉树
// Definition for a binary tree node.
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
可以直接解决如下题目:
-
0102.二叉树的层序遍历
-
0199.二叉树的右视图
-
0637.二叉树的层平均值
-
0104.二叉树的最大深度 (迭代法)
-
0111.二叉树的最小深度(迭代法)
-
0222.完全二叉树的节点个数(迭代法)
public int countNodes(TreeNode root) {
if(root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}