java使用栈构造二叉树(不会构造二叉树的看进来)
遍历就很简单了 大家自己遍历遍历就行
感觉题目其实表达的不是特别清楚 我第一次构造树的时候就搞错了
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int rootVal = in.nextInt();
// 使用栈来构造二叉树
TreeNode root = new TreeNode(rootVal);
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
int fa = in.nextInt();
int lch = in.nextInt();
int rch = in.nextInt();
TreeNode now = stack.pop();
if(rch != 0){
TreeNode right = new TreeNode(rch);
stack.push(right);
now.right = right;
}
if(lch != 0){
TreeNode left = new TreeNode(lch);
stack.push(left);
now.left = left;
}
}
// 调用递归
Main app = new Main();
app.preTraverse(root);
System.out.println();
app.nowTraverse(root);
System.out.println();
app.afterTraverse(root);
}
/*====================================递归=====================================*/
public void preTraverse(TreeNode root){
if(root == null) return;
System.out.print(root.val + " ");
preTraverse(root.left);
preTraverse(root.right);
}
public void nowTraverse(TreeNode root){
if(root == null) return;
nowTraverse(root.left);
System.out.print(root.val + " ");
nowTraverse(root.right);
}
public void afterTraverse(TreeNode root){
if(root == null) return;
afterTraverse(root.left);
afterTraverse(root.right);
System.out.print(root.val + " ");
}
static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val){
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right){
this.val = val;
this.left = left;
this.right = right;
}
}
}


京公网安备 11010502036488号