每日一道编程题(9):树的层次遍历

利用非递归方法求二叉树的高度

数据结构算法正在学习…

import java.util.Scanner;

class Node {
    int data;//数据域
    Node left; //该节点的左孩子
    Node right;//该节点的右孩子

    public Node(int data) {//构造方法
        this.data = data;
    }
}

//二叉树的非递归求高度
public class Main {
    public static void main(String[] args) {
        Node root = new Node(10);
        Node a = new Node(4);
        Node b = new Node(20);
        Node c = new Node(3);
        Node d = new Node(5);
        Node e = new Node(15);
        Node f = new Node(25);
        root.left = a;
        root.right = b;
        a.left = c;
        a.right = d;
        b.left = e;
        b.right = f;
        System.out.println(bTNonRecursiveHeight(root));
    }

    public static int bTNonRecursiveHeight(Node root) {
        int front = -1;//头
        int rear = -1;//尾
        int level = 0;//层数
        int last = 0;
        Node[] queue = new Node[1000]; //节点数组
        if (root == null) {
            return 0;
        }
        queue[++rear] = root;
        while (front < rear) {
            Node p = queue[++front];  //取出当前节点
            if (p.left != null) {
                queue[++rear] = p.left;//左孩子加入到数组里

            }
            if (p.right != null) {
                queue[++rear] = p.right;//右孩子加入到对象数组里面
            }
            if (front == last) { //当front == rear时 循环结束
                level++; //层数加一
                last = rear;
            }
        }
        return level;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_41033299/article/details/88879672