199. 二叉樹的右視圖

這道題非常的好。可以用depth-first search 以及breadth-first兩種解法。參考了

https://leetcode-cn.com/problems/binary-tree-right-side-view/solution/liang-chong-jie-ti-fang-fa-di-gui-ji-bai-100he-fei/

並且depth-first search 不是通常意義上的前序,後以及中序遍歷。並且要對depth 進行判斷。

breadth-first每次訪問的都是每層的最後一個元素,也就是最右邊的元素。

class Solution {

public:

    vector<int> ans;

    void depthSearch(TreeNode* root, vector<int>& res, int level){

        if(!root) return;

        if(res.size() == level) res.push_back(root->val);

        depthSearch(root->right, res, level+1);

        depthSearch(root->left, res, level+1); 

    }

    // this is for depth-first traverse

    vector<int> rightSideView1(TreeNode* root){

        int level(0);

        vector<int> res;

        if(!root) return res;

        res.push_back(root->val);

        depthSearch(root, res, level);

        return res;

    }

    // this is for breadth-first search 

    vector<int> rightSideView(TreeNode* root) {

        if(root == NULL) return ans;

        queue<TreeNode*> nodePath;

        nodePath.push(root);

        TreeNode* current = new TreeNode(0);

        while(!nodePath.empty()){

            ans.push_back(nodePath.back()->val);

            int queue_size = nodePath.size();

            while(queue_size--){

                current = nodePath.front(); nodePath.pop();

                if(current->left) nodePath.push(current->left);

                if(current->right) nodePath.push(current->right);

            }

        }     

        return ans;

        }

};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章