public bool IsBinaryTreeABST(BinaryTreeNode root) { Stack <BinaryTreeChecker> bstChecker = new Stack <BinaryTreeChecker>(); bstChecker.Push(new BinaryTreeChecker(root, int.MinValue, int.MaxValue)); while (bstChecker.Any()) { BinaryTreeChecker rangeChecker = bstChecker.Pop(); if (rangeChecker.BinaryTree != null && (rangeChecker.BinaryTree.Value < rangeChecker.lowerBound || rangeChecker.BinaryTree.Value > rangeChecker.upperBound)) { return(false); } if (rangeChecker.BinaryTree != null && rangeChecker.BinaryTree.Right != null) { BinaryTreeChecker rightRangeNode = new BinaryTreeChecker(rangeChecker.BinaryTree.Right, rangeChecker.BinaryTree.Value, rangeChecker.upperBound); bstChecker.Push(rightRangeNode); } if (rangeChecker.BinaryTree != null && rangeChecker.BinaryTree.Left != null) { BinaryTreeChecker leftRangeNode = new BinaryTreeChecker(rangeChecker.BinaryTree.Left, rangeChecker.lowerBound, rangeChecker.BinaryTree.Value); bstChecker.Push(leftRangeNode); } } return(true); }
public bool IsBinaryTreeABSTRecursionHelper(BinaryTreeChecker root) { if (root == null || root.BinaryTree == null) { return(true); } if (root != null && root.BinaryTree != null && (root.BinaryTree.Value < root.lowerBound || root.BinaryTree.Value > root.upperBound)) { return(false); } bool isLeftTree = this.IsBinaryTreeABSTRecursionHelper(new BinaryTreeChecker(root.BinaryTree.Left, root.lowerBound, root.BinaryTree.Value)); bool isRightTree = this.IsBinaryTreeABSTRecursionHelper(new BinaryTreeChecker(root.BinaryTree.Right, root.BinaryTree.Value, root.lowerBound)); return(isLeftTree && isRightTree); }