flatten-binary-tree-to-linked-li

2020-04-24  本文已影响0人  瞬铭

//https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

    //二叉树先序遍历变变变变变变变
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }

        flatten(root.left);

        flatten(root.right);

        TreeNode tmp = root.right;
        root.right = root.left;
        root.left = null;
        while (root.right != null) {
            root = root.right;
        }
        root.right = tmp;
    }
   // 这个为什么不能AC?????????
    TreeNode res = new TreeNode(-1);
    TreeNode tmp = res;

    public void flatten2(TreeNode root) {
        preO(root);
        root = res.right;
    }

    public void preO(TreeNode root) {
        tmp.right = new TreeNode(root.val);
        tmp = tmp.right;
        if (root.left != null) {
            preO(root.left);
        }

        if (root.right != null) {
            preO(root.right);
        }
    }
    public void flatten3(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten3(root.left);
        flatten3(root.right);

        TreeNode right = root.right;
        TreeNode tmp = root;
        root.right = root.left;
        root.left = null;
        while (tmp.right != null) {
            tmp = tmp.right;
        }
        tmp.right = right;
    }
上一篇下一篇

猜你喜欢

热点阅读