• 将二叉搜索树转换成一个排序的双向链表


    输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

    首先我们分析一下题目:首先定义左右两个链表节点,每次从右面插入节点,既然是一棵二叉搜索树那么最小的一定是最左面的节点,所以1、我们递归找到最左面的节点,先放一个节点。2、递归二叉树的右节点,有则插入节点。

    定义节点:

    public class TreeNode {
       int val = 0;
       TreeNode left = null;
       TreeNode right = null;
       public TreeNode(int val) {
           this.val = val;
       }
    }
    //递归调用 左 根 右 遍历
    public class Solution {
        //双向链表的左边头结点和右边头节点
       TreeNode leftHead = null;
       TreeNode rightHead = null;
       public TreeNode Convert(TreeNode pRootOfTree) {
            //递归调用叶子节点的左右节点返回null
           if(pRootOfTree==null) return null;
            //第一次运行时,它会使最左边叶子节点为链表第一个节点
           Convert(pRootOfTree.left);
           if(rightHead==null){
               leftHead= rightHead = pRootOfTree;
           }else{
               //把根节点插入到双向链表右边,rightHead向后移动
              rightHead.right = pRootOfTree;
              pRootOfTree.left = rightHead;
              rightHead = pRootOfTree;
           }
            //把右叶子节点也插入到双向链表(rightHead已确定,直接插入)
           Convert(pRootOfTree.right);
            //返回左边头结点
           return leftHead;
       }
    }
  • 相关阅读:
    leetcode[164] Maximum Gap
    leetcode[162] Find Peak Element
    leetcode[160] Intersection of Two Linked Lists
    leetcode[156] binary tree upside down
    leetcode[155] Min Stack
    leetcode Find Minimum in Rotated Sorted Array II
    leetcode Find Minimum in Rotated Sorted Array
    leetcode Maximum Product Subarray
    ROP
    windbg bp condition
  • 原文地址:https://www.cnblogs.com/ScarecrowAnBird/p/6728495.html
Copyright © 2020-2023  润新知