My Cpp Solution


  • 0
    K

    /**

    • 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:

    int hieght(TreeNode *root){
        if(root==NULL)
            return 0;
        int lh=hieght(root->left);
        int rh=hieght(root->right);
        return lh>rh?lh+1:rh+1;
    }
    void levelOrder(TreeNode* root,vector<vector<int>> &a,int level,int index){
        if(root==NULL)
            return;
        if(level==0){
            //cout<<root->val<<" ";
            a[index].push_back(root->val);
        }
        if(index%2==0){
            levelOrder(root->left,a,level-1,index);
            levelOrder(root->right,a,level-1,index);
        }
        else{
            levelOrder(root->right,a,level-1,index);
            levelOrder(root->left,a,level-1,index);
        }
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        int h=hieght(root),i;
        vector<vector<int>> a;
        a.resize(h);
        
        for(i=0;i<h;i++)
            levelOrder(root,a,i,i);
        
        return a;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.