关于树的一些算法题---持续更新

树的定义为:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

求一棵树的高度:

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

判断一棵树是否为平衡树:

    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

删除二叉搜索树中的某个结点:

public TreeNode deleteNode(TreeNode root, int key) {
    if(root == null){
        return null;
    }

    if(key < root.val) {
        root.left = deleteNode(root.left, key);
    } else if (key > root.val) {
        root.right = deleteNode(root.right, key);
    } else {
        if(root.left == null) {
            return root.right;
        } else if(root.right == null) {
            return root.left;
        }  // 上面两个判断处理了待删除结点是叶子结点或者只有一个孩子结点的情况
        
        // 下面处理待删除结点有两个孩子结点的情况
        TreeNode minNode = findMin(root.right);  // 首先找到右子树中最小的结点
        root.val = minNode.val;                  // 替换该节点,替换后是满足二叉搜索树的性质
        root.right = deleteNode(root.right, root.val); // 删除替换结点
    }
    return root;
}

private TreeNode findMin(TreeNode node){
    while(node.left != null) {
        node = node.left;
    }
    return node;
}

计算二叉树结点的个数:

    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        return 1 + countNodes(root.left) + countNodes(root.right);
    }

将一棵BST中的每个节点值加上所有大于该节点值的值:

class Solution {
    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root != null) {
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
        }
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_22158743/article/details/88749788
今日推荐