获取二叉树高度

记录几种获取二叉树高度的实现方法,代码仅java实现。
二叉树结构定义为:

    public class Node {
        char val;
        Node left;
        Node right;

        public Node(){}

        public Node(int val) {
            this.val = val;
        }
    }

递归

public static int calTreeHeight(Node root) {
        if (root == null)
            return 0;
        return Math.max(calTreeHeight(root.left), calTreeHeight(root.right)) + 1;
    }

非递归

基于按层遍历的思想

public static int calTreeHeight(Node root) {
        if (root == null)
            return 0;
        Queue<Node> nodes = new LinkedList<>();
        nodes.offer(root);
        int visitedNum = 0;
        int enQueueNum = 1;
        int levelNodeNum = 1;
        int height = 0;
        while(!nodes.isEmpty()) {
            Node node = nodes.poll();
            visitedNum++;
            if (node.left != null) {
                nodes.offer(node.left);
                enQueueNum++;
            }
            if (node.right != null) {
                nodes.offer(node.right);
                enQueueNum++;
            }
            if (visitedNum == levelNodeNum) {
                levelNodeNum = enQueueNum;
                height++;
            }
        }
        return height;
    }

基于后序遍历思想

public static int calTreeHeight(Node root) {
        int height = 0;
        Stack<Node> nodes = new Stack<>();
        Stack<Integer> tag = new Stack<>();
        while(root != null || !nodes.isEmpty()) {
            // 先遍历左孩子
            while(root != null) {
                nodes.push(root);
                tag.push(0);
                root = root.left;
            }
            if (tag.peek() == 1) {
                height = Math.max(height, nodes.size());
                nodes.pop();
                tag.pop();
                root = null;
            } else {
                root = nodes.peek();
                root = root.right;
                tag.pop();
                tag.push(1);
            }
        }
        return height;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值