-
(1)算法分析:获取头节点的值。把头结点的值带入函数进行比较。
-
当某个节点有左子树,进入左子树比较。当有右子树的时候,进入右子树比较。
-
#include
#include
#include}
Node()
{
this->lChild = nullptr;
this->rChild = nullptr;
}
};
Node *createTree(int intarr[], int length, int i)
{
Node *root = nullptr;
if (i < length && intarr[i] != -1)
{
root = new Node(intarr[i]);
root->lChild = createTree(intarr, length, i * 2 + 1);
root->rChild = createTree(intarr, length, i * 2 + 2);
}
return root;
}
bool isUnivaluedBinaryTree(Node *root,int key)
{
if (root->val != key)
{
return false;
}
if (root->lChild)
{
return isUnivaluedBinaryTree(root->lChild, key);
}
if (root->rChild)
{
return isUnivaluedBinaryTree(root->rChild, key);
}
return true;
}
int main()
{
int intarr[5] = { 2,2,2,5,2 };
Node *root = createTree(intarr, 5, 0);
int key = root->val;
cout << isUnivaluedBinaryTree(root, key) << endl;
system(“pause”);
return 0;
}