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

    此题以前看过,就是中序遍历。相当于有一个排序的数组里面有两个数字调换了,有两种情况,调换的数字相邻和不相邻。

    public class Solution {
        public void recoverTree(TreeNode root) {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode n = root;
            TreeNode last = null;
            TreeNode current = null;
            TreeNode n1 = null;
            TreeNode n2 = null;
            while (n != null || !stack.empty()) {
                if (n != null) {
                    stack.push(n);
                    n = n.left;
                }
                else {
                    n = stack.pop();
                    // visit n
                    last = current;
                    current = n;
                    if (last != null && current != null && last.val > current.val) {
                        if (n1 == null) {
                            n1 = last;
                            n2 = current;
                        }
                        else {
                            n2 = current;
                        }
                    }
                    n = n.right;
                }
            }
            if (n1 != null && n2 != null) {
                int tmp = n1.val;
                n1.val = n2.val;
                n2.val = tmp;
            }
        }
    }
    

      

  • 相关阅读:
    hrbust1279
    U盘快捷方式中毒处理办法
    计算几何
    poj1113
    凸包模版
    STL容器
    HDU2048
    HDU2047
    HDU2045
    python面试题总结
  • 原文地址:https://www.cnblogs.com/lautsie/p/3262885.html
Copyright © 2011-2022 走看看