(Java)leetcode-897 Increasing Order Search Tree(递增顺序查找树)

你的名字 2023-02-14 10:23 206阅读 0赞

题目描述

给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。

示例 :
在这里插入图片描述

提示:

给定树中的结点数介于 1 和 100 之间。
每个结点都有一个从 0 到 1000 范围内的唯一整数值。

思路1

中序遍历二叉树,同时新建一颗二叉树,随着遍历的进行,不断往右孩子中填值。

代码

  1. class Solution {
  2. private TreeNode newTree = new TreeNode();
  3. private TreeNode index = newTree;
  4. public TreeNode increasingBST(TreeNode root) {
  5. if (root == null) return null;
  6. increasingBST(root.left);
  7. newTree.right= new TreeNode(root.val);
  8. newTree = newTree.right;
  9. increasingBST(root.right);
  10. return index.right;
  11. }
  12. }

在这里插入图片描述

思路2

不用新建树,直接修改指针。

代码

  1. class Solution {
  2. TreeNode prev=null, head=null;
  3. public TreeNode increasingBST(TreeNode root) {
  4. if(root==null) return null;
  5. increasingBST(root.left);
  6. if(prev!=null) {
  7. root.left=null; // we no longer needs the left side of the node, so set it to null
  8. prev.right=root;
  9. }
  10. if(head==null) head=root; // record the most left node as it will be our root
  11. prev=root; //keep track of the prev node
  12. increasingBST(root.right);
  13. return head;
  14. }
  15. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,206人围观)

还没有评论,来说两句吧...

相关阅读

    相关 897. 递增顺序查找

    给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。 示例 : 输入:[5,3,6,2,4,nul