https://leetcode.com/problems/balanced-binary-tree/
이진 트리 주어졌을 때 균형 잡힌 여부 반환
왼쪽 오른쪽 height 확인해서 차이가 2이상일 때 false로 반환
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool answer;
public bool IsBalanced(TreeNode root) {
answer = true;
if (root == null) return true;
Traverse(root, 0);
return answer;
}
public int Traverse(TreeNode node, int height)
{
// 답 확정되면 밑에 과정 필요없으므로 그냥 넘기기 위함
if (!answer) return 0;
int leftHeight = height;
int rightHeight = height;
if (node.left != null && node.right != null)
{
leftHeight = Traverse(node.left, height + 1);
rightHeight = Traverse(node.right, height + 1);
}
else if (node.left != null)
{
leftHeight = Traverse(node.left, height + 1);
}
else if (node.right != null)
{
rightHeight = Traverse(node.right, height + 1);
}
else
{
return height;
}
if (Math.Abs(leftHeight - rightHeight) >= 2) answer = false;
return Math.Max(leftHeight, rightHeight);
}
}