Lintcode 二叉树的锯齿形层次遍历

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

您在真实的面试中是否遇到过这个题? Yes
样例
给出一棵二叉树 {3,9,20,#,#,15,7},

3
/ \
9 20
/ \
15 7
按照从下往上的层次遍历为:

[
[15,7],
[9,20],
[3]
]

思路:在题 二叉树的层次遍历 http://blog.csdn.net/thinkerleo1997/article/details/77370131 的基础上引入了 一个脉冲变化的‘锯齿数’,当二叉树换层数后‘锯齿数’会取相反数,这时会改变这层二叉树读入的方式

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
        // write your code here
                vector< vector<int> > re;
        if(root == NULL){
            return re;
        }
        queue<TreeNode*> que; 
        que.push(root); 
        int should_len = 1; 
        int null_len = 0;
        int sawtooth_num = 1; //引入 锯齿数
        vector<int> now_s; 
        while(!que.empty()){
            TreeNode *t = que.front();
            que.pop();
            if (t == NULL){
                null_len ++;
            }
            else{

                if(sawtooth_num == 1) //根据锯齿数来控制插入方式
                {
                    now_s.insert(now_s.end(), t->val);            
                }
                else
                {
                    now_s.insert(now_s.begin(), t->val);
                }
                que.push(t->left);
                que.push(t->right);

            }
            if(should_len == null_len + now_s.size()     
                && now_s.size() != 0){
                re.insert(re.end(), now_s);  
                now_s.clear();  
                should_len *= 2;  
                null_len *= 2;  
                sawtooth_num = -sawtooth_num; //二叉树换层后锯齿数取负数

                }
            }
        return re;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值