欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(Java)leetcode-897 Increasing Order Search Tree

程序员文章站 2022-03-16 08:42:37
...

题目描述

Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

(Java)leetcode-897 Increasing Order Search Tree
(Java)leetcode-897 Increasing Order Search Tree

思路1

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

代码

class Solution {
	private TreeNode newTree = new TreeNode();
	private TreeNode index = newTree;
    public TreeNode increasingBST(TreeNode root) {   	
        if (root == null) return null;
        increasingBST(root.left);
        newTree.right= new TreeNode(root.val);
        newTree = newTree.right;
        increasingBST(root.right);
        return index.right;
    }
}

(Java)leetcode-897 Increasing Order Search Tree

思路2

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

代码

class Solution {
	TreeNode prev=null, head=null;
    public TreeNode increasingBST(TreeNode root) {
        if(root==null) return null;   
        increasingBST(root.left);  
        if(prev!=null) { 
        	root.left=null; // we no  longer needs the left  side of the node, so set it to null
        	prev.right=root; 
        }
        if(head==null) head=root; // record the most left node as it will be our root
        prev=root; //keep track of the prev node
        increasingBST(root.right); 
        return head;
    }
}

(Java)leetcode-897 Increasing Order Search Tree