剑指offer67题-No59.按之字形顺序打印二叉树

二叉树的层序遍历,特判版。
特判还是比较难的,主要是需要用到tmp.insert(tmp.begin(), x->val);实现从右到左打印

class Solution {
public:
vector > Print(TreeNode* pRoot) {

    if (pRoot == nullptr) return {};

    vector<vector<int>> res;
    queue<TreeNode*> Q;
    Q.push(pRoot);
    int odd = 0;
    vector<int> tmp;

    while (!Q.empty()) {
        tmp.clear();
        int len = Q.size();
        for(int i = 0; i < len; ++i){
            TreeNode* x = Q.front();
            Q.pop();

            if(x == nullptr) continue;
            Q.push(x->left);
            Q.push(x->right);
            // 保持左右孩子入队不变,打印的时候需要特判
            if(odd % 2 == 0){
                // 第一行 从左到右打印
                tmp.push_back(x->val);
            }else{
                // 这样可以实现从右向左打印
                tmp.insert(tmp.begin(), x->val);
            }
        }
        odd++;
        if(!tmp.empty()) res.push_back(tmp);
    }
    return res;
}
};
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇