记不住的二叉树类型
- 完全二叉树:complete binary tree
A Complete Binary Tree (CBT) is a binary tree in which every level,
except possibly the last, is completely filled, and all nodes
are as far left as possible.
- 平衡二叉搜索树 (AVL tree)
the heights of the two subtrees of any node differ by at most one.
二叉树的遍历方式
-
深度优先遍历
- 前序遍历(递归法,迭代法)
- 中序遍历(递归法,迭代法)
- 后序遍历(递归法,迭代法)
-
广度优先遍历
- 层次遍历(迭代法)
- 二叉树的中序遍历 迭代法:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
while(!stack.isEmpty() || node != null) {
if(node != null) {
stack.push(node);
node = node.left;
} else {
node = stack.pop();
res.add(node.val);
node = node.right;
}
}
return res;
}
}
使用迭代法需要一个指针和一个栈 指针是用来遍历节点的,栈是用来储存遍历的节点
-
二叉树的层序遍历
-
翻转二叉树 invert binary tree
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
这道题关键是要弄懂是前序/中序/后序遍历, 可以使用前序/后序,但是不能使用中序,因为中序是先是翻转了左边,然后中间,再翻转右边,但是这步操作会造成左边已经翻转完了,等到了右边又反转回去了,然后原先右边的那棵子树完全没有翻转。
- 验证二叉搜索树
class Solution {
TreeNode max = null;
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
boolean left = isValidBST(root.left);
if(max != null && max.val >= root.val) {
return false;
} else {
max = root;
}
boolean right = isValidBST(root.right);
return left && right;
}
}
中序遍历 然后比较中间的值时表示大于左边的最大值,不到万不得已不要看答案 自己想