1. 程式人生 > >二叉樹層序遍歷應用之Binary Tree Right Side View

二叉樹層序遍歷應用之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]

.

Solutions:

易想到求的是每層中最右的一個節點。

二叉樹層序遍歷過程中,每次迴圈開始時,佇列中存放的剛好是將要訪問的一層的節點。

/**
 * 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;
		if(root==NULL){
			return result;
		}		
        queue<TreeNode*> Q;
		Q.push(root);
		TreeNode *right;
		while(!Q.empty()) {
			int Qsize=Q.size();
			for(int i=0; i<Qsize; ++i) {
				right=Q.front();
				Q.pop();
				if(right->left != NULL){
					Q.push(right->left);
				}
				if(right->right != NULL){
					Q.push(right->right);
				}
			}
			result.push_back(right->val);
		}
    }
};