解題心得
用 array 存 node,找高度從 root 往下走直到 leaf node,leaf node 要回傳 0 給 parent,parent 選最大的加一後再往上丟。
程式碼
#include <iostream>
using namespace std;
struct Node
{
int left, right;
};
Node tree[31];
int height(int index)
{
if (index == -1)
return 0;
else
{
int leftHeight = height(tree[index].left);
int rightHeight = height(tree[index].right);
if (leftHeight > rightHeight) return leftHeight + 1;
else return rightHeight + 1;
}
}
int main()
{
int n, u, a, b, root = -1;
cin >> n;
while (n--)
{
cin >> u >> a >> b;
tree[u].left = a; tree[u].right = b;
if (root == -1) root = u;
}
cout << height(root) - 1 << endl;
return 0;
}
沒有留言:
張貼留言