力扣0099——恢复二叉搜索树

恢复二叉搜索树

难度:中等

题目描述

给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树

示例1

输入: root = [1,3,null,null,2]
输出:[3,1,null,null,2]

示例2

输入: root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]

题解

因为二叉搜索树的性质可得,将其中序遍历存储到列表中,数值为单调递增,由此可以得到以下步骤

  • 遍历列表,找到递增中断点
  • 再次遍历列表,找到中断点应该在的位置
  • 将两个数值进行交换

完成之后即为所求

想法代码

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution
{
    IList<TreeNode> travelList = new List<TreeNode>();
    public static void Main(String[] args)
    {
        TreeNode root = new TreeNode(3)
        {
            left = new TreeNode(1),
            right = new TreeNode(4)
            {
                left = new TreeNode(2)
            }

        };
        Solution solution = new Solution();
        solution.RecoverTree(root);
        foreach (var a in solution.travelList)
        {
            Console.Write(a.val + " ");
        }
    }

    public void RecoverTree(TreeNode root)
    {
        Travel(root);
        int index1 = 1;
        int index2 = 0;
        while (index1 < travelList.Count)
        {
            if (travelList[index1].val > travelList[index1 - 1].val)
            {
                index1++;
            }
            else
            {
                break;
            }
        }

        while (index2 < travelList.Count)
        {
            if (travelList[index2].val > travelList[index1 - 1].val)
            {
                break;
            }

            index2++;
        }
        TreeNode treeNode1 = travelList[index1 - 1];
        TreeNode treeNode2 = travelList[index2 - 1];
        int val1 = treeNode1.val;
        int val2 = treeNode2.val;
        treeNode1.val = val2;
        treeNode2.val = val1;
    }

    public void Travel(TreeNode root)
    {
        if (root == null)
        {
            return;
        }

        Travel(root.left);
        travelList.Add(root);
        Travel(root.right);
    }
}
avel(root.left);
        travelList.Add(root);
        Travel(root.right);
    }
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值