常见算法 - 二叉搜索树与双向链表

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

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

    }

}
*/
public class Solution {
    //左侧子树的尾节点
    public static TreeNode leftLast;
    public TreeNode Convert(TreeNode root) {
         if (root == null){
             return null;
         } 
        if (root.left == null && root.right == null) {
            leftLast = root;
            return root;
        }
            TreeNode left = Convert(root.left);
            if(left != null) {
                leftLast.right = root;
                root.left = leftLast;
            }
     
        leftLast = root;

            TreeNode right = Convert(root.right);
            if(right != null) {
                root.right = right;
                right.left = root;
            }
        
        return left != null ? left : root;
    }
}

猜你喜欢

转载自blog.csdn.net/b9x__/article/details/81873684
今日推荐