各类算法基础模板
一、二分查找法
二、KMP
三、二叉树
// 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;
}
}
二叉树的深度优先遍历
广度优先遍历(队列)
可以直接解决如下题目:
二叉树深度
二叉树节点数量
public int countNodes(TreeNode root) {
if(root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}