Loading

897. 递增顺序查找树-未解决

897. 递增顺序查找树

https://leetcode-cn.com/contest/weekly-contest-100/problems/increasing-order-search-tree/

package com.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author stono
 * @date 2018/9/2
 * 897. 递增顺序查找树
 * https://leetcode-cn.com/contest/weekly-contest-100/problems/increasing-order-search-tree/
 */
public class Lesson897 {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(5);
        TreeNode t2 = new TreeNode(3);
        TreeNode t3 = new TreeNode(6);
        TreeNode t4 = new TreeNode(2);
        TreeNode t5 = new TreeNode(4);
        TreeNode t6 = new TreeNode(8);
        TreeNode t7 = new TreeNode(1);
        TreeNode t8 = new TreeNode(7);
        TreeNode t9 = new TreeNode(9);
        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t2.right = t5;
        t3.right = t6;
        t4.left = t7;
        t6.left = t8;
        t6.right = t9;
        TreeNode.printNode(t1);
        TreeNode treeNode = increasingBST(t1);
        System.out.println();
        TreeNode.printNode(treeNode);
    }

    public static TreeNode increasingBST(TreeNode root) {
        TreeNode left = root;
        while (true) {
            if (left.left != null) {
                left = left.left;
            }else {
                break;
            }
        }

        List<Integer> list = new ArrayList<>(8);
        addAllValue(root, list);
        // 排序
        Collections.sort(list);
        TreeNode temp = left;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) - left.val == 0) {
                continue;
            }
            TreeNode t2 = new TreeNode(list.get(i));
            temp.right = t2;
            temp = t2;
        }
        return left;
    }

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

 

posted @ 2018-09-02 16:39  stono  阅读(176)  评论(0编辑  收藏  举报