【LeetCode】114. 二叉树展开为链表(JAVA)

原题地址:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/

题目描述:
给定一个二叉树,原地将它展开为链表。

例如,给定二叉树

在这里插入图片描述

将其展开为:

在这里插入图片描述

解题方案:
和Morris有点像,不过是把root的左子树放到右边,再将原来的右子树接到原左子树的最右结点上。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        while(root != null)
        {
            if(root.left != null)
            {
                TreeNode tmp = root.right;
                root.right = root.left;
                root.left = null;
                TreeNode t = root.right;
                while(t.right != null)
                {
                    t = t.right;
                }
                t.right = tmp;
            }
            root = root.right;
        }
    }
}
发布了110 篇原创文章 · 获赞 4 · 访问量 9320

猜你喜欢

转载自blog.csdn.net/rabbitsockx/article/details/104687259