JZ26 Binary search tree and doubly linked list

Title description

Enter a binary search tree and convert the binary search tree into a sorted doubly linked list. ClaimCannot create any new nodes, Can only adjust the point of the node pointer in the tree.

Ideas

Binary tree uses recursion, the code is concise and not easy to make mistakes.

ready

  • Understand the binary search tree (a friend who doesn’t know how to use Baidu)
  • Cannot create any new nodes, The blogger understands the meaning of this sentence is that the topic does not want to store the traversed value in the newly created binary tree, but hopes to realize it by operating the pointer.
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    
    TreeNode pre = null;		//每次递归之后用来保存双向链表头节点
    TreeNode tail = null;		//每次递归之后用来保存双向链表尾节点
    public TreeNode Convert(TreeNode pRootOfTree) {
    
    			//创建根节点为pRootOfTree的双向链表,返回头节点
        if (pRootOfTree == null) {
    
    		//递归的终止条件
            return null;
        }
        Convert(pRootOfTree.left);		//返回左子树的双向链表
        if (tail == null) {
    
    
            pre = pRootOfTree;
            tail = pRootOfTree;
        }else {
    
    
            tail.right = pRootOfTree;
            pRootOfTree.left  = tail;
            tail = pRootOfTree;
        }
        Convert(pRootOfTree.right);		//返回右子树的双向链表
        return pre;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/108676264