zoukankan      html  css  js  c++  java
  • [leetcode]Recover Binary Search Tree

    Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake.

    Recover the tree without changing its structure.

    Note:
    A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 

    算法思路:

    思路1:求出中序遍历序列,空间复杂度O(n),tip要求只可以开O(1)空间。

    代码略

    思路2:中序遍历,遇到每个点,都记录其前驱,记录当前指针cur的前一个节点pre,如果pre.val大于cur.val,表示有错序,多数情况错序有两次;如果有一次错序,说明就是相邻节点需要被交换。

     1 public class Solution {
     2     TreeNode first = null,second = null,pre = null;
     3     public void recoverTree(TreeNode root) {
     4         findNode(root);
     5         swap(first, second);
     6     }
     7     private void findNode(TreeNode root){
     8         if(root == null){
     9             return;
    10         }
    11         if(root.left != null )  findNode(root.left);
    12         if(pre != null && root.val < pre.val){
    13             if(first == null){
    14                 first = pre;
    15             }
    16             second = root;
    17         }
    18         pre = root;
    19         if(root.right != null)  findNode(root.right);
    20     }
    21     private void swap(TreeNode node1,TreeNode node2){
    22         int tem = node1.val;
    23         node1.val = node2.val;
    24         node2.val = tem;
    25     }
    26 }
  • 相关阅读:
    5、流程控制
    4、字典和元祖
    3、列表操作
    2、字符串和数据类型
    1.标识符练习
    使用xpath提取页面所有a标签的href属性值
    网页提取所有邮箱
    正则表达式
    提取包含QQ的文本为QQ邮箱
    python继承小demo
  • 原文地址:https://www.cnblogs.com/huntfor/p/3881570.html
Copyright © 2011-2022 走看看