【Binary tree】Verify binary search tree

0x00 topic

Given a binary tree
, determine whether it is a valid二叉搜索树

A binary search tree has the following 特征:
A node 's subtree contains only 小于the current node's tree
A node 's subtree contains only 大于the current node's tree All
subtrees and subtrees must also be二叉搜索树


0x01 Ideas

Binary search tree, 中序traversal, is an 升序array
to 当前compare 上一个the size of the value of the node with the value of the node, you can


0x02 solution

language:Swift

tree node:TreeNode

public class TreeNode {
    public var val: Int
    public var left: TreeNode?
    public var right: TreeNode?
    public init() { self.val = 0; self.left = nil; self.right = nil; }
    public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
    public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
        self.val = val
        self.left = left
        self.right = right
    }
}

solution:

func isValidBST(_ root: TreeNode?) -> Bool {
    // 记录前一个节点的值
    var pre = Int.min
    
    func dfs(_ root: TreeNode?) -> Bool {
        guard let root = root else {
            return true
        }
        
        // 前序遍历位置
        let left = dfs(root.left)
        
        // 中序遍历位置
        // 大于当前节点,则返回 false
        if pre >= root.val {
            return false
        }else{
            // 记录当前节点值
            pre = root.val
        }
        
        // 后序遍历位置
        let right = dfs(root.right)
        
        // 返回 左子树 与 右子树 的结果
        return left && right
    }
    
    return dfs(root)
}


small notes

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/122856140