二叉树的中序遍历
题目描述
思路
先序遍历:当第一次访问的时候就进行打印
中序遍历:当第二次访问的时候就进行打印
后序遍历:当第三次访问的时候就进行打印
二叉树的存储方式一般分为顺序存储结构和链式存储结构,在Java里则分别用数组和一个包含值,左、右孩子成员变量的类来表示。顺序存储结构一般用来存储完全二叉树,否则可能会浪费很多空间。
(以后要注意代码的结构哈 清晰明了)
题解
public class BinaryTreeLDR94 {
public TreeNode initNodes(){
TreeNode e = new TreeNode(5,null,null);
TreeNode d = new TreeNode(4,null,null);
TreeNode c = new TreeNode(3,null,null);
TreeNode b = new TreeNode(2,c,e);
TreeNode a = new TreeNode(1,b,d);
return a;
}
public void solution1(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while(!stack.empty()||curr!=null){
if (curr!=null){
stack.push(curr);
curr = curr.getLeft();
}else{
curr = stack.pool();
System.out.println(curr);
curr = curr.getRight();
}
}
}
//递归算法是如此的清新 真的是服气呀 为何会如此神奇 谁发明的 牛批
public void solution2(TreeNode root){
if(root.getLeft()!=null){
solution2(root.getLeft());
}
System.out.println(root.toString());
if(root.getRight()!=null){
solution2(root.getRight());
}
}
public static void main(String[] args) {
BinaryTreeLDR94 binaryTreeLDR94 = new BinaryTreeLDR94();
TreeNode root = binaryTreeLDR94.initNodes();
//非递归实现
binaryTreeLDR94.solution1(root);
System.out.println("-----------------------");
//递归实现
binaryTreeLDR94.solution2(root);
}
}