[LeetCode-15]Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:mac给iphone充电 编辑:程序博客网 时间:2024/06/05 14:06

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its zigzag level order traversal as:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

Analysis:
The idea is much similar to the previous question "Binary Tree Level Order Traversal", the only difference is the print order for each level. Note that we store the level order while traverse the tree, otherwise the print could be a mass. Just consider the order when pushing the values into the result vector. for each level could use a bool flag to identify whether store it in which order.

public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();ArrayList<TreeNode> temp = new ArrayList<TreeNode>();if(root == null) return result;temp.add(root);boolean flag = true;int index = 0;int nextLevCount = 1;while(index<temp.size()){int curLevCount = nextLevCount;nextLevCount = 0;ArrayList<Integer> level = new ArrayList<Integer>();for(int i = index;i<index+curLevCount;i++){root = temp.get(i);level.add(root.val);if(root.left!=null){nextLevCount++;temp.add(root.left);}if(root.right!=null){nextLevCount++;temp.add(root.right);}}if(flag)result.add(level);elseresult.add(reverseArray(level));flag = flag ? false:true;index+=curLevCount;}return result;    }public ArrayList<Integer> reverseArray(ArrayList<Integer> nodeList){int start = 0;int end = nodeList.size()-1;while(start<end){int n1 = nodeList.get(start);int n2 = nodeList.get(end);nodeList.set(start, n2);nodeList.set(end, n1);start++;end--;}return nodeList;}

c++

use reverse in STL to reverse vector

vector<vector<int> > zigzagLevelOrder(TreeNode *root) {    vector<vector<int>> result;    vector<TreeNode*> sta;    if(root == NULL) return result;    sta.push_back(root);    int nextLevCou = 1;    int index = 0;    bool order = false;    while(index < sta.size()){        int curLevCou = nextLevCou;        nextLevCou = 0;        vector<int > level;        for(int i = index; i<index+curLevCou; i++){            root = sta[i];            level.push_back(root->val);            if(root->left != NULL){                sta.push_back(root->left);                nextLevCou++;            }            if(root->right !=NULL){                sta.push_back(root->right);                nextLevCou++;            }        }        if(!order){            result.push_back(level);        }else{            reverse(level.begin(), level.end());            result.push_back(level);        }        order = order ? false:true;        index = index+curLevCou;    }    return result;    }



0 0