[leetcode] 199. Binary Tree Right Side View 解题报告

题目链接:https://leetcode.com/problems/binary-tree-right-side-view/

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].


思路:先找出树的高度,然后按照先遍历右子树,再遍历左子树的顺序,依次找出在每一层的代表的结点。

代码如下:

/**
 * 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 getHeight(TreeNode* root)//计算树的高度
    {
        if(!root) return 0;
        return max(getHeight(root->left), getHeight(root->right)) + 1;
    }
    void search(TreeNode* root, int &num, int height, int curHeight)
    {
        if(!root || num >= height) return;
        if(num < curHeight)//如果这个高度还没有值,则将当前值赋给他
        {
            num++;
            result.push_back(root->val);
        }
        search(root->right, num, height, curHeight+1);//先搜右子树
        search(root->left, num, height, curHeight+1);//再搜左子树
    }
    vector<int> rightSideView(TreeNode* root) {
        if(!root) return result;
        int height = getHeight(root);
        int num = 0;
        search(root, num, height, 1);
        return result;
    }
private:
    vector<int> result;
};


你可能感兴趣的:(LeetCode,tree,binary)