LeetCode - 二叉树从右边看(字节跳动模拟面试)

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

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

using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


void print(vector &r){
    for(int i=0;i rightSideView(TreeNode* root) {
        vector level;
        vector ret;
        vector extend;
        if(root==NULL){
            return ret;
        }
        level.push_back(0);
        extend.push_back(root);
        int i = 0;
        while(ileft && p->right){
                    level.push_back(level[i]);
                    extend.push_back(p->left);
                    level.push_back(level[i]);
                    extend.push_back(p->right);
                }else if(p->left){
                    level.push_back(level[i]);
                    extend.push_back(p->left);
                }else if(p->right){
                    level.push_back(level[i]);
                    extend.push_back(p->right);
                }
            }
            i++;
        }
        int c = -1;
        for(int i=level.size()-1;i>=0;i--){
            if(i==level.size()-1){
                c = level[i];
                ret.push_back(extend[i]->val);
            }else if(level[i]val);
            }
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};

int main(){
    Solution s;
    TreeNode root(1);
    TreeNode left(2);
    TreeNode right(3);
    TreeNode leftt(4);
    root.left = &left;
    root.right = &right;
    left.left = &leftt;
    vectorret = s.rightSideView(&root);
    print(ret);
    return 0;
}

非递归版,AC100%

你可能感兴趣的:(LeetCode - 二叉树从右边看(字节跳动模拟面试))