🌕 114. 二叉树展开为链表

吞佛童子2022年10月10日
  • algorithm
  • tree
小于 1 分钟

🌕 114. 二叉树展开为链表

难度: 🌕

问题描述

img_31.png


解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        // 思路:
        // 若左子树非空,将左子树拼接在右子树处,右子树拼接在左子树的最右子节点
        // 移动 cur,cur = root.right 继续下一个节点的调整工作
        mySol(root);
    }

    private void mySol(TreeNode root) {
        // 递归终止条件
        if(root == null) {
            return;
        }
        if(root.left == null) {
            mySol(root.right);
            return;
        }
        // root.left != null
        if(root.right == null) {
            root.right = root.left;
            root.left = null;
            mySol(root.right);
            return;
        }
        // root.left != null && root.right != null
        TreeNode right = root.right;
        TreeNode left = root.left;
        root.right = left;
        root.left = null;
        TreeNode cur = root.right;
        while(cur.right != null) {
            cur = cur.right; // 找到最右子节点
        }
        cur.right = right;
        mySol(root.right);
    }
}

输出

img_30.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou