遍历二叉树
遍历二叉树
二叉树的定义
二叉树是由n个结点所构成的集合,它或为空树,或为非空树。
对于非空树:
(1)、有且仅有一个称之为根的结点
(2)、除了根以外其余的结点分为两个互不相交的子集T1和T2,分别称为左子树和右子树,他们本身有都是二叉树。遍历二叉树具体方法
1、先序遍历:先根结点再左子树后右子树
代码实现:
① 递归
public void preTree(TreeNode tree) {
if(tree != null) {
System.out.println(tree.val);
preTree(tree.left);
preTree(tree.right);
}
}
②非递归
public void preTree1(TreeNode tree) {
TreeNode p = tree;
LinkedList<TreeNode> stack = new LinkedList<>();
while(p != null || !stack.isEmpty()) {
if(p != null) {
stack.push(p);
System.out.println(p.val);
p = p.left;
} else {
p = stack.pop();
p = p.right;
}
}
}
2、中序遍历:先左再根后右
代码实现:
①递归
public void inorder(TreeNode root) {
if(root != null) {
inorder(root.left);
System.out.println(root.val);
inorder(root.right);
}
}
②非递归
public void inorder01(TreeNode root) {
TreeNode p = root;
LinkedList<TreeNode> stack = new LinkedList<>();
while(p != null || !stack.isEmpty()) {
if(p != null) {
stack.push(p);
p = p.left;
} else {
p = stack.pop();
System.out.println(p.val);
p = p.right;
}
}
}
3、后序遍历:先左再右后根
代码实现:
①递归
public void lastorder(TreeNode root) {
if(root != null) {
lastorder(root.left);
lastorder(root.right);
System.out.println(root.val);
}
}
②非递归
public void lastorder02(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
if(root == null) return;
TreeNode p = root;
stack.push(p);
stack.push(p);
while(!stack.isEmpty()) {
p = stack.getFirst();
stack.pop();
if(!stack.isEmpty() && p == stack.getFirst()) {
if(p.right != null) {
stack.push(p.right);
stack.push(p.right);
}
if(p.left != null) {
stack.push(p.left);
stack.push(p.left);
}
} else {
list.add(p.val);
}
}
}
先把根压入栈底,再右子树,后左子树,然后再出栈,顺序就是左右根啦,连续压入两次的目的是,第一次弹出如若弹出的元素跟栈顶元素相同,可以判断该结点的子树还没遍历。以上~
4、层次遍历:层层遍历,应该不难,容易理解
public void layerorder(TreeNode root) {
if(root == null) return;
LinkedList<TreeNode> list = new LinkedList<>();
ArrayList<Integer> list1 = new ArrayList<>();
TreeNode p = root;
list.add(p);
list1.add(p.val);
while(!list.isEmpty()) {
p = list.pop();
if(p.left != null) {
list.add(p.left);
list1.add(p.left.val);
}
if(p.right != null) {
list.add(p.right);
list1.add(p.right.val);
}
}
}
- 总结
递归的方法代码简洁很多,就是递归的思想比较难理解。