二叉树的种类
满二叉树
如果一颗二叉树只有度为0的结点和度为2的结点, 并且度为0的结点在同一层上,则这颗二叉树为满二叉树
这棵二叉树为满二叉树,也可以说深度为k,有2^k-1个节点的二叉树。
完全二叉树
在完全二叉数中,除了最底层结点可能没有填满外,其余每层结点数都达到最大值 并且最下面一层的结点都集中在盖层最左边的若干位置,并且连续,若最底层为第h层 则该层包含1~2^(h-1)个结点
二叉搜索树
二叉搜索树是有数值的,并且因为他是有数值的,二叉搜索树是一个有序树
- 若他的左子树不空,则左子树所有的结点的值都小于它跟结点的值
- 若他的右子树不空,则右子树所有的结点的值都大于它的跟结点的值
- 它的左右子树也分别是二叉排序树
平衡二叉搜索树
又被称为AVL(Adelson-Velsky and Landis) 树,且有以下性质 它是一个空树或他的左右两个子树的高度差绝对值不超过1 并且左右两个子树都是一个平衡二叉树
144. 二叉树的前序遍历
题目描述
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例
输入:root = [1,null,2,3]
输出:[1,2,3]
定义
public class TreeNode {
int val;
TreeNode left;
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 List<Integer> solution(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root, result);//确定递归参数跟返回值
return result;
}
private void preorder(TreeNode root, List<Integer> result) {
if (root == null) {return;}//终止条件
result.add(root.val);
preorder(root.left, result);//单层递归的逻辑
preorder(root.right, result);//单层递归的逻辑
}
145. 二叉树的后序遍历
题目描述
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例
输入:root = [1,null,2,3]
输出:[3,2,1]
算法实现
public List<Integer> solution(TreeNode root) {
List<Integer> result = new ArrayList<>();
postOrder(root, result);
return result;
}
private void postOrder(TreeNode root, List<Integer> result) {
if (root == null) {return;}
postOrder(root.left, result);
postOrder(root.right, result);
result.add(root.val);
}
94. 二叉树的中序遍历
题目描述
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例
输入:root = [1,null,2,3]
输出:[1,3,2]
算法实现
public List<Integer> solution(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorder(root, result);
return result;
}
private void inorder(TreeNode root, List<Integer> result) {
if (root == null) {return;}
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}