larscheng / algo

0 stars 0 forks source link

【Check 54】2024-04-17 - 114. 二叉树展开为链表 #156

Open larscheng opened 5 months ago

larscheng commented 5 months ago

114. 二叉树展开为链表

larscheng commented 5 months ago

思路

}



### 复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(n)
larscheng commented 5 months ago

思路

从根节点开始遍历,如果有左子树,则找左子树最右侧节点指向当前节点的右节点,

当前节点左子树置为null,右子树指向原左子树

代码

class Solution {

    public void flatten(TreeNode root) {
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left != null) {
                TreeNode next = curr.left;
                TreeNode predecessor = next;
                while (predecessor.right != null) {
                    predecessor = predecessor.right;
                }
                predecessor.right = curr.right;
                curr.left = null;
                curr.right = next;
            }
            curr = curr.right;
        }
    }
}

复杂度