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

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

 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;
    }

你可能感兴趣的:(二叉树几种操作(递归实现))