LeetCode Flatten Binary Tree to Linked List

来源:互联网 发布:阿里云 idc资质 编辑:程序博客网 时间:2024/05/29 18:03

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1        / \       2   5      / \   \     3   4   6

The flattened tree should look like:
   1    \     2      \       3        \         4          \           5            \             6

click to show hints.

题意:将一个二叉搜索树整成递增链表。

思路:首先我们能想到先序遍历的过程,所以我们要想办法将左子树最大的节点连接上右子树。然后为了变成链表所以我们将左子树置null,在这之前要将左子树移到右子树这边,类推下去处理。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {        private void make(TreeNode root) {if (root.left == null) return;TreeNode tmp = root.left;while (tmp.right != null) tmp = tmp.right;tmp.right = root.right;root.right = root.left;root.left = null;}    public void flatten(TreeNode root) {       if (root == null) return;              TreeNode tmp = root;       while (tmp.right != null || tmp.left != null) {       make(tmp);       tmp = tmp.right;       }    }}



0 0
原创粉丝点击