题目描述:
给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
题目来源于Leetcode :https://leetcode-cn.com/problems/increasing-order-search-tree/
解题思路:
- 先用中序遍历将二叉树的结点值存入一个数组中,然后定义一个新的树头结点,遍历数组并将数组元素存入新树的右子树,然后新树的右子树。
/**
* 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 TreeNode increasingBST(TreeNode root) {
List<Integer> arr = new ArrayList<Integer>();
inorder(root, arr);
//定义新树的头结点
TreeNode newTree = new TreeNode(0);
TreeNode cur = newTree;
for (int value : arr) {
//通过遍历将原来二叉树的值存入新树的右子树
cur.right = new TreeNode(value);
cur = cur.right;
}
return newTree.right;
}
//中序遍历将二叉树结点值存入arr数组中
public void inorder(TreeNode root, List<Integer> arr) {
if (root == null) return;
inorder(root.left, arr);
arr.add(root.val);
inorder(root.right, arr);
}
}
解题思路:
- 定义一个cur当前结点,采用中序遍历的方法遍历二叉树,将二叉树的左子树结点设置为空,cur不断指向二叉树的右子树,这样一来,等二叉树遍历结束后,cur就是新的二叉树了,只要返回cur的右子树即可。
/**
* 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 {
TreeNode cur;
public TreeNode increasingBST(TreeNode root) {
TreeNode newTree = new TreeNode(0);
cur = newTree;
inorder(root);
return newTree.right;
}
public void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
node.left = null;
cur.right = node;
cur = node;
inorder(node.right);
}
}