二叉树几种操作(递归实现)

前序、中序、后序遍历二叉树

 public static void preOrder(TreeNode node) {
        System.out.println(node.val);
        if (node.left != null) {
            preOrder(node.left);
        }
        if (node.right != null) {
            preOrder(node.right);
        }
    }

二叉树所有节点的最大值

public static int maxNode(TreeNode node) {
        int left = Integer.MIN_VALUE;
        int right = Integer.MIN_VALUE;
        if (node.left != null) {
            left = maxNode(node.left);
        }
        if (node.right != null) {
            right = maxNode(node.right);
        }
        return Math.max(Math.max(left, right), node.val);
    }

二叉树的高

public static int highTree(TreeNode node) {
        int left = 0;
        int right = 0;
        if (node.left != null) {
            left = highTree(node.left);
        }
        if (node.right != null) {
            right = highTree(node.right);
        }
        return Math.max(left+1,right+1);
    }

二叉树所有节点和

public static int sumTree(TreeNode node) {
        int left = 0;
        int right = 0;
        if (node.left != null) {
            left = sumTree(node.left);
        }
        if (node.right != null) {
            right = sumTree(node.right);
        }
        return left+right+node.val;
    }
    原文作者:twilight_b5be
    原文地址: https://www.jianshu.com/p/192d70f263f9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞