二叉搜索树与双向链表&&阶乘末尾0的数量&&找到搜索二叉树中两个错误的节点

211 阅读1分钟

NC64 二叉搜索树与双向链表

题目链接

1、解题思路

使用树的中序遍历,处理细节就好。

2、代码
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    private TreeNode preNode;

    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        TreeNode left = getLeft(pRootOfTree);
        inOrder(pRootOfTree);
        return left;
    }

    private TreeNode getLeft(TreeNode pRootOfTree) {

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

    private void inOrder(TreeNode pRootOfTree) {
        if (pRootOfTree.left != null) {
            inOrder(pRootOfTree.left);
        }
        pRootOfTree.left = preNode;
        if (preNode != null) {
            preNode.right = pRootOfTree;
        }
        preNode = pRootOfTree;
        if (pRootOfTree.right != null) {
            inOrder(pRootOfTree.right);
        }
    }
}

NC129 阶乘末尾0的数量

题目链接

1、解题思路

只要算这些数有多少因子5就可以了,2肯定比5多。

2、代码
import java.util.*;


public class Solution {
    /**
     * the number of 0
     * @param n long长整型 the number
     * @return long长整型
     */
    public long thenumberof0 (long n) {
        long base = 5;
        long ans = 0;
        while (base <= n) {
            ans = ans + n / base;
            base = base * 5;
        }
        return ans;
    }
}

NC58 找到搜索二叉树中两个错误的节点

题目链接

1、解题思路

先按照中序遍历,遍历出来数组,然后在数组中找到两个异常点即可。

2、代码
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root
     * @return int整型一维数组
     */
    public int[] findError(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inOrder(list, root);
        int before = 0;
        int last = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) > list.get(i + 1)) {
                before = list.get(i);
                last = list.get(i + 1);
                for (int j = i + 1; j < list.size(); j++) {
                    if (list.get(j) < last) {
                        last = list.get(j);
                    }
                }
                break;
            }
        }
        return new int[]{last, before};
    }

    private void inOrder(List<Integer> list, TreeNode root) {
        if (root.left != null) {
            inOrder(list, root.left);
        }
        list.add(root.val);
        if (root.right != null) {
            inOrder(list, root.right);
        }
    }
}