199:Binary Tree Right Side View【樹】【DFS】【BFS】

題目鏈接:click~

/*題意:給出一個二叉樹,假設你站在樹的最右側,求能看到的數*/

/**
 *思路:DFS遍歷整棵樹,先判斷當前結點是否是最右側的,接着遍歷
 *      右子樹,再左子樹。
 */


class Solution {
public:
    void GetView(TreeNode *root, vector<int> &v, int level) {//level表示第幾層
        if(root == NULL) return;
        if(level == v.size())         //是最右側的結點
            v.push_back(root->val);
        GetView(root->right, v, level+1);
        GetView(root->left, v, level+1);
    }
    vector<int> rightSideView(TreeNode *root) {
        vector<int> v;
        if(root == NULL) return v;
        GetView(root, v, 0);
        return v;
    }
};


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