지그재그 인쇄 이 진 트 리(자바 재 귀적 실현)
6015 단어 알고리즘 분석 및 디자인 자바 구현
결점 클래스:
class TreeNode{
int val;// value
TreeNode left;//
TreeNode right;//
public TreeNode(int val) {
this.val = val;
}
}
출력 방법 구체 적 실현:
public static void print(TreeNode root){
if (root == null) {
System.out.println(" null");
return;
}
int level = 1;//
Stack stackOne = new Stack<>();//
stackOne.push(root);
printTree(level,stackOne);
}
/**
*
* @param level
* @param from
*/
public static void printTree(int level,Stack from){
if (from == null || from.empty()) {
return;
}
//
Stack to = new Stack<>();
System.out.print(level+" : ");
// ,
if (level %2 != 0) {
while(!from.empty()){
TreeNode node = from.pop();
if (node != null) {
System.out.print(node.val+"\t");
if (node.left != null) {
to.push(node.left);
}
if (node.right != null) {
to.push(node.right);
}
}
}
}else{
// ,
while(!from.empty()){
TreeNode node = from.pop();
// null,
if (node != null) {
System.out.print(node.val+"\t");
if (node.right != null) {
to.push(node.right);
}
if (node.left != null) {
to.push(node.left);
}
}
}
}
System.out.println();
//
printTree(++level,to);
}
테스트:
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode one = new TreeNode(2);
TreeNode two = new TreeNode(3);
TreeNode three = new TreeNode(4);
TreeNode four = new TreeNode(5);
TreeNode five = new TreeNode(6);
TreeNode six = new TreeNode(7);
root.left=one;
root.right=two;
one.left=three;
one.right=four;
two.left=five;
two.right=six;
print(root);
}
출력 결과:
1 : 1
2 : 3 2
3 : 4 5 6 7