1.二叉树的定义
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
2.二叉树的遍历
2.1 深度优先遍历
2.1.1 前序遍历(根左右)
递归:
//前序遍历--递归
public void preOrderTraversal(TreeNode root){
if (root==null){
return;
}
System.out.print(root.val+" ");
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
非递归:
//前序遍历--非递归
public void preOrderTraversal(TreeNode root){
if (root==null){
return;
}
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while (cur != null || !stack.empty()){
while (cur!=null){
stack.push(cur);
System.out.print(cur.val+" ");
cur=cur.left;
}
TreeNode top=stack.pop();
cur=top.right;
}
}
2.1.2 中序遍历(左根右)
递归:
//中序遍历--递归
public void inOrderTraversal(TreeNode root){
if (root==null){
return;
}
inOrderTraversal(root.left);
System.out.print(root.val+" ");
inOrderTraversal(root.right);
}
非递归:
//中序遍历--非递归
public void inOrderTraversal(TreeNode root){
if (root==null){
return;
}
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while (cur != null || !stack.empty()){
while (cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.pop();
System.out.print(top.val+" ");
cur=top.right;
}
}
2.1.3 后序遍历(左右根)
递归:
//后序遍历--递归
public void posOrderTraversal(TreeNode root){
if (root==null){
return;
}
posOrderTraversal(root.left);
posOrderTraversal(root.right);
System.out.print(root.val+" ");
}
非递归:
//后序遍历--非递归
public void posOrderTraversal(TreeNode root){
if (root==null){
return;
}
TreeNode prev=null;
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while (cur != null || !stack.empty()){
while (cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.peek();
cur=top.right;
if (cur==null || cur.val==prev.val){
System.out.print(top.val+" ");
prev=stack.pop();
cur=null;
}
}
}
2.2 广度优先遍历----层次遍历
//层次遍历--用队列实现
public void levelOrder(TreeNode root){
if (root==null){
return;
}
LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
TreeNode cur=null;
queue.offer(root);//将根节点入队
while (!queue.isEmpty()){
//对头元素出队并访问
cur=queue.poll();
System.out.print(cur.val+" ");
//如果当前节点的左节点不为空入队
if (cur.left!=null){
queue.offer(cur.left);
}
//如果当前节点的右节点不为空入队
if (cur.right!=null){
queue.offer(cur.right);
}
}
}
参考文章: