반응형

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region Question 4.5 | |
/* | |
* 어떤 이진 트리가 이진 탐색 트리인지 판별하는 함수를 구현하라. | |
*/ | |
/// <summary> | |
/// <paramref name="root"/>가 이진 탐색 트리가 맞는지 판별한다. | |
/// </summary> | |
/// <param name="root">검사할 이진 트리</param> | |
/// <returns><paramref name="root"/>가 이진 트리가 맞다면 <code>true</code>를 반환한다.</returns> | |
public static bool Q5_CheckBST(BinaryTreeNode<IComparable> root) | |
{ | |
return CheckBST(root, null, null); | |
} | |
private static bool CheckBST(BinaryTreeNode<IComparable> node, IComparable min, IComparable max) | |
{ | |
if(node == null) { return true; } | |
if( (min != null && node.Data.CompareTo(min) <= 0) || (max != null && node.Data.CompareTo(max) >= 0)) | |
{ | |
return false; | |
} | |
if(!CheckBST(node.Left, min, node.Data) || !CheckBST(node.Right, node.Data, max)) | |
{ | |
return false; | |
} | |
return true; | |
} | |
#endregion |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void Q4_5() | |
{ | |
BinaryTreeNode<IComparable> root = new BinaryTreeNode<IComparable>(0) | |
{ | |
Left = new BinaryTreeNode<IComparable>(1) | |
{ | |
Left = new BinaryTreeNode<IComparable>(3), | |
Right = new BinaryTreeNode<IComparable>(4), | |
}, | |
Right = new BinaryTreeNode<IComparable>(2) | |
}; | |
Assert.IsFalse(TreeGraph.Q5_CheckBST(root)); | |
root = new BinaryTreeNode<IComparable>(4) | |
{ | |
Left = new BinaryTreeNode<IComparable>(2) | |
{ | |
Left = new BinaryTreeNode<IComparable>(1), | |
Right = new BinaryTreeNode<IComparable>(3) | |
}, | |
Right = new BinaryTreeNode<IComparable>(6) | |
{ | |
Left = new BinaryTreeNode<IComparable>(5), | |
Right = new BinaryTreeNode<IComparable>(7) | |
} | |
}; | |
Assert.IsTrue(TreeGraph.Q5_CheckBST(root)); | |
} |
반응형
'Develop > 코딩인터뷰' 카테고리의 다른 글
[코딩인터뷰] 문제 4.7 (0) | 2018.02.10 |
---|---|
[코딩인터뷰] 문제 4.6 (0) | 2018.02.10 |
[코딩인터뷰] 문제 4.4 (0) | 2018.01.22 |
[코딩인터뷰] 문제 4.3 (0) | 2018.01.22 |
프로그래밍 면접 이렇게 준비한다 (0) | 2017.05.18 |
꾸준히 노력하는 개발자 "김예건" 입니다.