🚩LeetCode 典中典

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    public static void quickSort(int[] nums, int left, int right) {
        if (left < right) {
            // 基准点
            int pivot = partition(nums, left, right);
            // 分治递归
            quickSort(nums, left, pivot - 1);
            quickSort(nums, pivot + 1, right);
        }
    }

    private static int partition(int[] nums, int left, int right) {
        // 随机选取一个元素作为基准
        int pivot = nums[left];
        int i = left, j = right + 1;
        while (true) {
            // 从左往右找第一个大于 pivot 的数
            while (nums[++i] < pivot && i < right) {
            }
            // 从右往左找第一个小于 pivot 的数
            while (nums[--j] > pivot && j > left) {
            }
            if (i >= j) {
                break;
            }
            swap(nums, i, j);
        }
        swap(nums, left, j);
        return j;
    }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
   public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        for (TreeNode cur = root; cur != null || !stack.isEmpty(); cur = cur.right) {
            // 一直下到最左
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();// 每次出栈的就是中序遍历顺序的节点,然后在以下进行对应操作
            res.add(cur.val);
            // 最后向右一步
        }
        return res;
    }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class BinaryTreePreorderTraversal {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(node.val);

            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }

        return result;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(0, node.val);  // 插入到结果列表的首部

            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        return result;
    }
0%