二叉树的遍历
二叉树的前序,中序,后序,层序遍历
package 剑指offer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author WangXiaoeZhe
* @Date: Created in 2019/11/22 18:11
* @description:
*/
public class Main17 {
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
ArrayList<Integer> resultList = new ArrayList<>();
/**
* 前序遍历:ABDEC
* 1.首先遍历左子树,遍历到叶子结点为止
* @return
* */
public boolean preorderTraverse(TreeNode node) {
//首先从根节点开始遍历
resultList.add(node.val);
if (node.left != null) {
preorderTraverse(node.left);
}
if (node.right != null) {
preorderTraverse(node.right);
}
return true;
}
/**
* 中序遍历:DBEAC
* @return
*
* */
public boolean inorderTarverse(TreeNode node) {
if (node.left != null) {
inorderTarverse(node.left);
}
resultList.add(node.val);
if (node.right != null) {
inorderTarverse(node.right);
}
return true;
}
/**
* 后序遍历:DEBCA
* @return
*
* */
public boolean postorderTarverse(TreeNode node) {
if (node.left != null) {
postorderTarverse(node.left);
}
if (node.right != null) {
postorderTarverse(node.right);
}
resultList.add(node.val);
return true;
}
/**
* 层序遍历
*
* @param root
* @return
*/
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if (root == null) {
return resultList;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode nowNode = q.peek();
q.poll();
resultList.add(nowNode.val);
if (nowNode.left != null) {
q.add(nowNode.left);
}
if (nowNode.right != null) {
q.add(nowNode.right);
}
}
return resultList;
}
}