leetcode_Validate 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.

解题思路

题目的意思就是判断一个给定的二叉树是不是二叉搜索树,二叉搜索树要求对每个节点,其左儿子节点数值小于父节点数值,右儿子节点数值大于父节点数值,并且左侧子树上的数值都小于父节点,右侧子树所有数值都大于父节点,也就是按此规则严格有序的,实际上我们中序遍历便可得到从小到大排序的元素序列,这里我们通过对中序遍历得到的List进行判断是否有来决定此二叉树是否为二叉搜索树。(这里涉及二叉搜索树和线序遍历有序两个概念的充分必要性,可以自行证明)

详细代码

二叉树的前中后序遍历通过递归可以很简单地写出代码,leetcode上也有要求迭代实现的,后续也会讲解。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
        //Validate Binary Search Tree
    //Given a binary tree, determine if it is a valid binary search tree (BST).
    public boolean isValidBST(TreeNode root) 
    {


        ArrayList<Integer> resultList = inorderTraversal(root);
        if(resultList.size()>=2)
        {
            for (int i = 0; i < resultList.size()-1; i++)
            {
                if (resultList.get(i)>=resultList.get(i+1))
                {
                    return false;
                }
            }
        }
            return true;

    }

    //recursively do it  middle order
  public ArrayList<Integer> inorderTraversal(TreeNode root) 
  {
    ArrayList<Integer> results = new ArrayList<Integer>();
    if(root == null)
    {
        return results;
    }
    else 
    {   
        results.addAll(inorderTraversal(root.left));//traverse left 
        results.add(root.val);//traverse the parent node
        results.addAll(inorderTraversal(root.right));//traverse right
        return results;
    }
  }
}

总结

这里需要理解二叉搜索树的概念,类似地如何建立二叉搜索树(BST),二叉搜索树地插入删除操作也是需要研究的,当然有兴趣滴可以去研究下,平衡二叉树(AVL),红黑树(RBT),字典树(TRIE)等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值