struct Node
{
Node* m_child[2];
int m_i;
};
int getSum(struct Node* pRoot)
{
if (!pRoot)
{
return 0;
}
return pRoot->m_i + getSum(pRoot->m_child[0]) + getSum(pRoot->m_child[1]);
}
int getSum1(struct Node* pRoot)
{
std::stack<struct Node*> s;
struct Node* p = pRoot;
int nSum = 0;
while (p != NULL || !s.empty())
{
while(p != NULL)
{
nSum += p->m_i;
s.push(p);
p = p->m_child[0];
}
if (!s.empty())
{
p = s.top();
s.pop();
p = p->m_child[1];
}
}
return pRoot->m_i + getSum(pRoot->m_child[0]) + getSum(pRoot->m_child[1]);
}
算法学习-二叉树节点和两种实现方法,递归非递归
最新推荐文章于 2020-11-08 15:25:46 发布