返回介绍

lcci / 04.05.Legal Binary Search Tree / README

发布于 2024-06-17 01:04:43 字数 6488 浏览 0 评论 0 收藏 0

面试题 04.05. 合法二叉搜索树

English Version

题目描述

实现一个函数,检查一棵二叉树是否为二叉搜索树。

示例 1:

输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
  / \
  3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
  根节点的值为 5 ,但是其右子节点值为 4 。

解法

方法一

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, x):
#     self.val = x
#     self.left = None
#     self.right = None


class Solution:
  res, t = True, None

  def isValidBST(self, root: TreeNode) -> bool:
    self.isValid(root)
    return self.res

  def isValid(self, root):
    if not root:
      return
    self.isValid(root.left)
    if self.t is None or self.t < root.val:
      self.t = root.val
    else:
      self.res = False
      return
    self.isValid(root.right)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  private boolean res = true;
  private Integer t = null;
  public boolean isValidBST(TreeNode root) {
    isValid(root);
    return res;
  }

  private void isValid(TreeNode root) {
    if (root == null) {
      return;
    }
    isValid(root.left);
    if (t == null || t < root.val) {
      t = root.val;
    } else {
      res = false;
      return;
    }
    isValid(root.right);
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
  bool isValidBST(TreeNode* root) {
    TreeNode* pre = nullptr;
    TreeNode* cur = root;
    stack<TreeNode*> stk;
    while (cur || !stk.empty()) {
      if (cur) {
        stk.push(cur);
        cur = cur->left;
      } else {
        cur = stk.top();
        stk.pop();
        if (pre && pre->val >= cur->val) {
          return false;
        }
        pre = cur;
        cur = cur->right;
      }
    }
    return true;
  }
};
func isValidBST(root *TreeNode) bool {
  stack := make([]*TreeNode, 0)
  var prev *TreeNode = nil
  node := root
  for len(stack) > 0 || node != nil {
    for node != nil {
      stack = append(stack, node)
      node = node.Left
    }
    node = stack[len(stack)-1]
    stack = stack[:len(stack)-1]
    if prev == nil || node.Val > prev.Val {
      prev = node
    } else {
      return false
    }
    node = node.Right
  }
  return true
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function isValidBST(root: TreeNode | null): boolean {
  let pre = -Infinity;
  const dfs = (root: TreeNode | null) => {
    if (root == null) {
      return true;
    }
    const { val, left, right } = root;
    if (!dfs(left) || val <= pre) {
      return false;
    }
    pre = val;
    return dfs(right);
  };
  return dfs(root);
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//   TreeNode {
//     val,
//     left: None,
//     right: None
//   }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, pre: &mut Option<i32>) -> bool {
    if root.is_none() {
      return true;
    }
    let root = root.as_ref().unwrap().borrow();
    if !Self::dfs(&root.left, pre) {
      return false;
    }
    if pre.is_some() && pre.unwrap() >= root.val {
      return false;
    }
    *pre = Some(root.val);
    Self::dfs(&root.right, pre)
  }

  pub fn is_valid_bst(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
    Self::dfs(&root, &mut None)
  }
}

方法二

func isValidBST(root *TreeNode) bool {
  return check(root, math.MinInt64, math.MaxInt64)
}

func check(node *TreeNode, lower, upper int) bool {
  if node == nil {
    return true
  }
  if node.Val <= lower || node.Val >= upper {
    return false
  }
  return check(node.Left, lower, node.Val) && check(node.Right, node.Val, upper)
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function isValidBST(root: TreeNode | null): boolean {
  if (root == null) {
    return true;
  }
  const { val, left, right } = root;
  const dfs = (root: TreeNode | null, min: number, max: number) => {
    if (root == null) {
      return true;
    }
    const { val, left, right } = root;
    if (val <= min || val >= max) {
      return false;
    }
    return dfs(left, min, Math.min(val, max)) && dfs(right, Math.max(val, min), max);
  };
  return dfs(left, -Infinity, val) && dfs(right, val, Infinity);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文