Binary Tree Right Side View

来源:互联网 发布:php小数转换为整数 编辑:程序博客网 时间:2024/06/03 02:39

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].

两种算法。

算法一:中序(但先右后左)dfs遍历,每次遍历一个节点时比较当前节点的高度与已看到的高度,若当前节点比已经看到的高度要高,则说明该节点是第一次被看到,加入到res中。此算法时间复杂度O(n),空间复杂度O(h)

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int curH = 0;  //已经看到的节点数    int tmpH = 1;  //当前访问节点的高度    vector<int> res;        void dfs(TreeNode *root){        if(root == NULL) return;        if(tmpH > curH){ res.push_back(root->val); curH++; }        if(root->right){ tmpH++; dfs(root->right); tmpH--; }        if(root->left){ tmpH++; dfs(root->left); tmpH--;}    }        vector<int> rightSideView(TreeNode *root) {        dfs(root);        return res;    }};

算法二:采用层次遍历,每次遍历到最右节点时,将该节点的值push_back到res中,此算法时间复杂度O(n),空间复杂度O(n)

/** * Definition for binary tree * 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> res;        if(root == NULL) return res;        TreeNode* nptr = NULL; //上下层次之间的标记        queue<TreeNode*> Q;        Q.push(root); Q.push(nptr);                while(!Q.empty()){            TreeNode* cur = Q.front();            Q.pop();            if(cur == nptr){                 if(Q.empty()) return res;  //全部遍历完毕                Q.push(nptr); continue; //否则只是将当前层遍历完毕            }            else if(Q.front() == nptr) res.push_back(cur->val);  //cur是本层最右节点            if(cur->left) Q.push(cur->left);            if(cur->right) Q.push(cur->right);        }                return res; //此行代码其实是多余的    }};


0 0