LeetCode (94): Mid-order traversal of binary trees & verifying binary search tree Binary Tree Inorder Traversal (Java)

Posted by rockstar_tom on Sun, 28 Jul 2019 07:22:44 +0200

2019.7.28 # Written Test Requirements for Programmers # LeetCode Organizes Personal Notes from Zero Single Brush (Continuous Update)

To verify whether a tree is a binary search tree is essentially to examine the middle order traversal (only the verification method of middle order traversal is the least costly).

The recursive algorithm is too simple to be implemented here. Cyclic words mainly need to pay attention to cyclic conditions and operating conditions.

Cyclic method

When the current node is not empty, the left subtree is constantly on the stack. When the current node is empty, the element goes out of the stack and traverses its right subtree. The current node and stack are empty, and the traversal ends.

Here we introduce a method of threading binary trees without stack (which can destroy the tree structure):

Morris Method

The basic principle of Morris Method is to iterate continuously, connect the root node of the first left subtree to the right node of its left subtree, and finally form a binary tree with only right subtree.

If the left subtree is empty, the right subtree is traversed. The first non-empty root node of the left subtree appears, making the pre the root node of the left subtree, and connecting curr to the rightmost node of the pre.

Portal: Mid-Rank Traversal of Binary Trees

Given a binary tree, return the inorder traversal of its nodes' values.

Follow up: Recursive solution is trivial, could you do it iteratively?

Given a binary tree, return its mid-order traversal.

Advanced: Recursive algorithm is very simple. Can you complete it by iterative algorithm?

Examples:
Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1, 3, 2]

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Given a binary tree, return the inorder traversal of its nodes' values.
 * Follow up: Recursive solution is trivial, could you do it iteratively?
 * Given a binary tree, return its mid-order traversal.
 * Advanced: Recursive algorithm is very simple. Can you complete it by iterative algorithm?
 */

public class BinaryTreeInorderTraversal {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    //Cyclic method
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        //The current node and stack are empty, and the traversal ends
        while(p != null || !stack.empty()){
            //When the current node is not empty, the left subtree keeps entering the stack
            while(p != null){
                stack.push(p);
                p = p.left;
            }
            //When the current node is empty, the element goes out of the stack and traverses its right subtree. If the right subtree is empty, its parent node will go out of the stack in the next loop.
            p = stack.pop();
            result.add(p.val);
            p = p.right;
        }
        return result;
    }

    //Morris Method: Binary Tree Threading Without Stack
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        TreeNode curr = root;
        //Continuous iterations connect the root node of the first left subtree to the rightmost node of its left subtree, and finally form a binary tree with only right subtree.
        while(curr != null){
            //If the left subtree is empty, then traverse the right subtree
            if(curr.left == null){
                result.add(curr.val);
                curr = curr.right;
            }
            //The first non-empty root node of the left subtree appears, making the pre the root node of the left subtree, and connecting curr to the rightmost node of the pre
            else{
                TreeNode pre = curr.left;
                while(pre.right != null){
                    pre = pre.right;
                }
                pre.right = curr;       //The root node is connected to the rightmost node of its left subtree
                TreeNode temp = curr;
                curr = curr.left;       //Current curr refers to the current root node (formerly pre)
                temp.left = null;       //The left subtree of the former root node is null
            }
        }
        return result;
    }
}


Portal: Verify Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.

The right subtree of a node contains only nodes with keys greater than the node's key.

Both the left and right subtrees must also be binary search trees.

Given a binary tree, it is judged whether it is an effective binary search tree.
Suppose a binary search tree has the following characteristics:

The left subtree of a node contains only fewer than the current number of nodes.

The right subtree of a node contains only more than the number of current nodes.

All left subtrees and right subtrees themselves must also be binary search trees.

Example 1:
Input:
    2
   / \
  1   3
 Output: true

Example 2:
Input:
    5
   / \
  1   4
     / \
    3   6
 Output: false
 Interpretation: The input is: [5,1,4,null,null,3,6].
     The root node has a value of 5, but its right child node has a value of 4.
/**
 * Given a binary tree, determine if it is a valid binary search tree (BST).
 * Assume a BST is defined as follows:
 * The left subtree of a node contains only nodes with keys less than the node's key.
 * The right subtree of a node contains only nodes with keys greater than the node's key.
 * Both the left and right subtrees must also be binary search trees.
 * Given a binary tree, it is judged whether it is an effective binary search tree.
 * Suppose a binary search tree has the following characteristics:
 * The left subtree of a node contains only fewer than the current number of nodes.
 * The right subtree of a node contains only more than the number of current nodes.
 * All left subtrees and right subtrees themselves must also be binary search trees.
 */

public class ValidateBinarySearchTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    //Morris algorithm
    public boolean isValidBST(TreeNode root) {
        //Prevent the occurrence of node values with one or more Integer.MIN_VALUE
        double last = -Double.MAX_VALUE;
        TreeNode curr = root;
        while(curr != null){
            if(curr.left == null){
                if(curr.val <= last){
                    return false;
                }
                last = curr.val;
                curr = curr.right;
            }
            else{
                TreeNode pre = curr.left;
                while(pre.right != null){
                    pre = pre.right;
                }
                pre.right = curr;
                TreeNode temp = curr.left;
                curr.left = null;
                curr = temp;
            }
        }
        return true;
    }

    //Recursive mid-order traversal
    double lastNum = -Double.MAX_VALUE;
    public boolean isValidBST2(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (isValidBST(root.left)) {
            if (lastNum < root.val) {
                lastNum = root.val;
                return isValidBST(root.right);
            }
        }
        return false;
    }
}



# Coding for an hour, Copying for a second. Leave a message of praise. Thank you.#

Topics: Java less