1. 二叉树的定义
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
构造二叉树
// 构造一颗树
public TreeNode initBinaryTree() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.left.right = new TreeNode(7);
root.right.left = new TreeNode(5);
root.right.right = new TreeNode(6);
root.right.right.left = new TreeNode(8);
return root;
}
2. 二叉树的递归遍历
2.1 二叉树递归先序遍历
// 递归 先序遍历 二叉树
public void recursiveFirstForeachBinaryTree(TreeNode root) {
if (root != null) {
System.out.print(root.val + "-->"); // 先访问根节点
if (root.left != null) {
recursiveFirstForeachBinaryTree(root.left);
}
if (root.right != null) {
recursiveFirstForeachBinaryTree(root.right);
}
}
}
2.2 二叉树递归中序遍历
// 递归 中序遍历 二叉树
public void recursiveMiddleForeachBinaryTree(TreeNode root) {
if(root==null) return;
if(root.left != null){//使用递归遍历左孩子
recursiveMiddleForeachBinaryTree(root.left);
}
System.out.print(root.val + "-->"); // 访问根节点
if(root.right != null){//使用递归遍历右孩子
recursiveMiddleForeachBinaryTree(root.right);
}
}
2.3 二叉树递归后序遍历
// 递归 后序遍历 二叉树
public void recursiveAfterForeachBinaryTree(TreeNode root) {
if(root==null) return;
if(root.left != null){//使用递归遍历左孩子
recursiveAfterForeachBinaryTree(root.left);
}
if(root.right != null){//使用递归遍历右孩子
recursiveAfterForeachBinaryTree(root.right);
}
System.out.print(root.val + "-->"); // 访问根节点
}
3. 二叉树的非递归遍历
3.1 非递归先序遍历二叉树
// 非递归 先序遍历 二叉树
public void nonRecursiveForeachBinaryTree(TreeNode root) {
if (root != null) {
Stack<TreeNode> stack = new Stack();
stack.push(root);
while (!stack.empty()) {
TreeNode top = stack.pop(); // 出栈顶元素
System.out.print("-->" + top.val);
// 入栈右节点
if (top.right != null) stack.push(top.right);
// 入栈左节点
if (top.left != null) stack.push(top.left);
}
}
}
3.2 非递归中序遍历二叉树
// 非递归 中序遍历 二叉树
public void nonRecursiveMiddleForeachBinaryTree(TreeNode root) {
if (root != null) {
Stack<TreeNode> stack = new Stack();
while (root!=null || !stack.empty()) {
if(root!=null){
stack.push(root);
root = root.left;
}else{
TreeNode node = stack.pop();
System.out.println(node.val+"-->");
root = node.right;
}
}
}
}
3.3 非递归后序遍历二叉树
public void nonRecursiveAfterForeachBinaryTree(TreeNode root) {
Stack<TreeNode> stackRes = new Stack<>();
Stack<TreeNode> stackTmp = new Stack<>();
stackTmp.push(root);
TreeNode curNode;
while (!stackTmp.isEmpty()) {
curNode = stackTmp.pop();
stackRes.push(curNode);
if (curNode.left != null) {
stackTmp.add(curNode.left);
}
if (curNode.right != null) {
stackTmp.add(curNode.right);
}
}
while (!stackRes.isEmpty()) {
System.out.print(stackRes.pop().val+"-->");
}
}