标签:
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题意:将一个二叉搜索树整成递增链表。
思路:首先我们能想到先序遍历的过程,所以我们要想办法将左子树最大的节点连接上右子树。然后为了变成链表所以我们将左子树置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; } } }
LeetCode Flatten Binary Tree to Linked List
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45643081