首先定义树的节点:
struct BinaryTreeNode
{int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight;
};
定义构建节点和连接节点的方法:
BinaryTreeNode* CreateBinaryTreeNode(int value)
{BinaryTreeNode* pNode = new BinaryTreeNode();pNode->m_nValue = value;pNode->m_pLeft = nullptr;pNode->m_pRight = nullptr;return pNode;
}void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{if(pParent != nullptr){pParent->m_pLeft = pLeft;pParent->m_pRight = pRight;}
}
构建二叉树实例:
// 1
// / \
// 2 3
// / \
// 4 5
// / \ / \
// 6 7 8 9
void Test1()
{TreeNode* pNode1 = CreateTreeNode(1);TreeNode* pNode2 = CreateTreeNode(2);TreeNode* pNode3 = CreateTreeNode(3);TreeNode* pNode4 = CreateTreeNode(4);TreeNode* pNode5 = CreateTreeNode(5);TreeNode* pNode6 = CreateTreeNode(6);TreeNode* pNode7 = CreateTreeNode(7);TreeNode* pNode8 = CreateTreeNode(8);TreeNode* pNode9 = CreateTreeNode(9);ConnectTreeNodes(pNode1, pNode2);ConnectTreeNodes(pNode1, pNode3);ConnectTreeNodes(pNode2, pNode4);ConnectTreeNodes(pNode2, pNode5);ConnectTreeNodes(pNode4, pNode6);ConnectTreeNodes(pNode4, pNode7);ConnectTreeNodes(pNode5, pNode8);ConnectTreeNodes(pNode5, pNode9);
}