LeetCode(103) Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:adobe 软件下载 编辑:程序博客网 时间:2024/06/08 01:16
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void dfs(TreeNode *root, int depth, vector<vector<int>> &result) {        if(root == NULL)            return;        if(result.size() < depth + 1) {            vector<int> tmp;            result.push_back(tmp);         }        result[depth].push_back(root->val);        if(root->left != NULL) {            dfs(root->left, depth + 1, result);        }        if(root->right != NULL) {            dfs(root->right, depth + 1, result);        }    }    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {        vector<vector<int>> result;        dfs(root, 0, result);        for(int i = 0; i < result.size(); i++) {            if((i % 2) == 1) {                reverse(result[i].begin(), result[i].end());            }        }        return result;    }};
0 0