• 剑指Offer_26_二叉搜索树与双向链表


    题目描述

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

    解题思路

    中序遍历就是数据递增(非递减)出现的,每次记录上一次出现的值,也即当前遍历结点的上一个结点。

    实现

    /*树结点的定义*/
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    }
    /*实现*/
    public class Solution {
        public TreeNode Convert(TreeNode pRootOfTree) {
            if (pRootOfTree == null) return pRootOfTree;
            TreeNode last = null;
            recursion(pRootOfTree, last);
    
            //寻找最前面的结点
            TreeNode node = pRootOfTree;
            while (node.left != null){
                node = node.left;
            }
            return node;
        }
    
        private TreeNode recursion(TreeNode pRootOfTree, TreeNode last) {
            if (pRootOfTree == null) return last;
    
            //遍历左子树
            if (pRootOfTree.left != null)
                last = recursion(pRootOfTree.left,last);
    
            //调整当前结点
            pRootOfTree.left = last;
            if (last != null)
                last.right = pRootOfTree;
            last = pRootOfTree;
    
            //遍历右子树
            if (pRootOfTree.right != null)
                last = recursion(pRootOfTree.right,last);
    
            return last;
        }
    }
    
  • 相关阅读:
    GeoServer与Spring MVC
    GeoServer二次开发1 hello Geoserver
    servlet的生命周期
    springboot打包出错,没有主清单
    空间数据库管理
    Gone with the wind
    谎言中的民众
    还是有些怀念这里啊
    MSN Protcol 学习笔记
    祝我的老师教师节快乐!
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5778945.html
Copyright © 2020-2023  润新知