文章目录
一、什么是二叉树?
二叉树是一棵空树,或者是一棵由一个根节点和两棵互不相交的,分别称作根的左子树和右子树组成的非空树;左子树和右子树又同样都是二叉树
二、遍历
1. Depth First Traversals
-
先序遍历 Pre-order
- Visit the root.
- Traverse the left subtree, i.e., call Preorder(left-subtree)
- Traverse the right subtree, i.e., call Preorder(right-subtree)
-
中序遍历 In-order
- Traverse the left subtree, i.e., call Inorder(left-subtree)
- Visit the root.
- Traverse the right subtree, i.e., call Inorder(right-subtree)
-
后序遍历 Post-order
- Traverse the left subtree, i.e., call Postorder(left-subtree)
- Traverse the right subtree, i.e., call Postorder(right-subtree)
- Visit the root.
2. Breadth First or Level Order Traversal
三、三种二叉树题型
1. 求值
从二叉树中求子数的值(depth, average, sum, lowest common ancestor, path)。
使用分治法,把左子树的值和右子树的值通过递归,传递给根节点。
有两种传递的方式:
- Return Value / Class (新建一个class来return多个值)
class ResultType {
...;
...;
public ResultType(...) {
...
}
}
private ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(...);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if (left...right) {
return new ResultType(...);
}
if (left...right) {
return new ResultType(...);
}
return new ResultType(...);
}
- Parameter (通过parameter把值传递给caller)
private void foo(TreeNode node, List<> list) {
if (node.left == null && node.right == null) {
list.add(...);
return;
}
if (node.left != null) {
foo(node.left, list);
}
if (node.right != null) {
foo(node.right, , list);
}
}
2. 结构变换
一般涉及到二叉树翻转,变成list或者string。
没有固定模版,根据情况使用BFS/DFS来解决。
3. 搜索
只需要记一个模版即可:
binary search tree iterator
先从根结点遍历二叉树搜索出一个起始点,然后用binary search tree iterator来搜就行。
四、题目
https://blog.csdn.net/Kejonho/article/details/109759581