gold-17-12


二叉树数据结构TreeNode可用来表示单向链表(其中left置空,right为下一个链表节点)。实现一个方法,把二叉搜索树转换为单向链表,要求依然符合二叉搜索树的性质,转换操作应是原址的,也就是在原始的二叉搜索树上直接修改。

返回转换后的单向链表的头节点。

注意:本题相对原题稍作改动

示例:

输入: [4,2,5,1,3,null,6,0]
输出: [0,null,1,null,2,null,3,null,4,null,5,null,6]

提示:

  • 节点数量不会超过 100000。

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode convertBiNode(TreeNode root) {
        if (root == null) {
            return root;
        }

        TreeNode head = getLeft(root);
        TreeNode leftN = getRight(root.left);
        TreeNode rightN = getLeft(root.right);
        convertBiNode(root.left);
        convertBiNode(root.right);
        if (leftN != null) {
            leftN.left = null;
            leftN.right = root;
        }
        root.left = null;
        if (rightN != null) {
            rightN.left = null;
        }
        root.right = rightN;
        return head;
    }

    private TreeNode getLeft(TreeNode node) {
        if (node == null) {
            return node;
        }

        TreeNode mostLeft = node;

        while (mostLeft.left != null) {
            mostLeft = mostLeft.left;
        }
        return mostLeft;
    }

    private TreeNode getRight(TreeNode node) {
        if (node == null) {
            return node;
        }

        TreeNode mostRight = node;

        while (mostRight.right != null) {
            mostRight = mostRight.right;
        }
        return mostRight;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !