剑指Offer算法实现之二十三:从上往下打印二叉树

题目:从上往下打印二叉树的每个节点,同一层的节点按照从左到右的顺序打印。二叉树节点定义如下:
struct BinaryTreeNode {
    int m_nValue;
    BinaryTreeNode *m_pLeft;
    BinaryTreeNode *m_pRight;
};

思路:

基本的广度优先遍历算法BFS,使用队列。对于每个待遍历的元素,先入队。对于队列的每个元素,出队访问之,并把其左右节点依次入队。

编译环境:ArchLinux+Clang3.3, C++11

实现一:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

struct BinaryTreeNode {
    int m_nValue;
    BinaryTreeNode *m_pLeft;
    BinaryTreeNode *m_pRight;
};

void printTreeBFS(BinaryTreeNode *pRoot)
{
    if (!pRoot) return;
    queue<BinaryTreeNode *>nodes;
    nodes.push(pRoot);
    while (!nodes.empty()) {
        BinaryTreeNode *pNode = nodes.front();
        cout << pNode->m_nValue << ' ';
        if (pNode->m_pLeft) nodes.push(pNode->m_pLeft);
        if (pNode->m_pRight) nodes.push(pNode->m_pRight);
        nodes.pop();
    }
}

/** 
 * 根据二叉树的单字符表示形式(形如"1(2,3(,4))")创建二叉树 
 * 区间:[start, end)
**/
BinaryTreeNode *createTree(const char *start, const char *end)
{
    if (start >= end) {
        return nullptr;
    }
    if (end - start == 1) {
        return new BinaryTreeNode{*start-'0', nullptr, nullptr};
    }
    const char *start1 = start+2;
    const char *end1 = start+2;
    int cnt = 0;
    while (true) {
        if (*end1 == '(') cnt++;
        if (*end1 == ')') cnt--;
        if (*end1 == ',' && cnt == 0) break;
        end1++;
    }
    const char *start2 = end1+1;
    const char *end2 = end1+1;
    cnt = 0;
    while (true) {
        if (*end2 == '(') cnt++;
        if (*end2 == ')' && cnt == 0) break;
        if (*end2 == ')') cnt--;
        end2++;
    }
    return new BinaryTreeNode{*start-'0', 
                    createTree(start1, end1),
                    createTree(start2, end2)};
}
/** Wrapper **/
BinaryTreeNode *createTree(const char *str)
{
    return createTree(str, str+strlen(str));
}
/** 打印二叉树 **/
void printTree(BinaryTreeNode *pRoot){
    if (!pRoot) return;
    cout << pRoot->m_nValue;
    if (pRoot->m_pLeft || pRoot->m_pRight) cout << '(';
    if (pRoot->m_pLeft) {
        printTree(pRoot->m_pLeft);
    }
    if (pRoot->m_pLeft && pRoot->m_pRight) cout << ',';
    if (pRoot->m_pRight) {
        printTree(pRoot->m_pRight);
    }
    if (pRoot->m_pLeft || pRoot->m_pRight) cout << ')';
}

int main()
{
    BinaryTreeNode *pRoot = createTree("8(6(5,7),1(9,2))");
    printTree(pRoot); cout << endl;
    printTreeBFS(pRoot);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值