当前位置:网站首页>Leetcode problem solving -- 99 Restore binary search tree

Leetcode problem solving -- 99 Restore binary search tree

2022-07-06 03:07:00 Snowy solitary boat

public void recoverTree(TreeNode root) {
    
    Stack<TreeNode> stack = new Stack<>();
    TreeNode node = root;
    TreeNode prev = null;
    TreeNode node1=null,node2=null;
    while (!stack.isEmpty()||node!=null){
    
        while (node!=null){
    
            stack.push(node);
            node = node.left;
        }
        node = stack.pop();
        if (prev!=null&&node.val<prev.val){
    
            if (node1==null){
    
                node1 = prev;
                node2 = node;
            }else {
    
                node2 = node;
            }
        }
        prev = node;
        node = node.right;
    }
    if (node1!=null&&node2!=null){
    
        int temp = node1.val;
        node1.val = node2.val;
        node2.val = temp;
    }
}

Ideas :
The topic is about switching nodes , In fact, there are only two possibilities , The exchanged nodes are adjacent , Or the exchanged nodes are not adjacent
The exchanged nodes are adjacent :
ai and ai+1 In exchange for , Then there is ai>ai+1 Save two nodes
Can we exchange two nodes directly at this time ? Not at all , Because there is another situation
ai and aj In exchange for , After exchanging
ai>ai+1,aj-1>aj
These two cases are found at the first node , If the situation is the same, we can save the two nodes in the first case , Then, if the next unqualified point appears, it will ai+1 use aj Replace
Then the same switch two nodes at the end of the loop

原网站

版权声明
本文为[Snowy solitary boat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132338038398.html