美文网首页Leetcode
Leetcode 199. Binary Tree Right

Leetcode 199. Binary Tree Right

作者: SnailTyan | 来源:发表于2018-09-20 18:25 被阅读5次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Binary Tree Right Side View

2. Solution

/**
 * 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:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> result;
        traverseRight(root, result, 0);
        return result;
    }

private:
    void traverseRight(TreeNode* root, vector<int>& result, int depth) {
        if(!root) {
            return;
        }
        depth++;
        if(depth > result.size()) {
            result.push_back(root->val);
        }
        traverseRight(root->right, result, depth);
        traverseRight(root->left, result, depth);
    }
};

Reference

  1. https://leetcode.com/problems/binary-tree-right-side-view/description/

相关文章

网友评论

    本文标题:Leetcode 199. Binary Tree Right

    本文链接:https://www.haomeiwen.com/subject/hounnftx.html