leecode 解题总结:199. Binary Tree Right Side View

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <queue>
using namespace std;
/*
问题:
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].

分析:给定一颗二叉树,想像你站在它的右边,返回你从右侧可以从顶部到底部看到的结点。
右边来看,这些顶点,能够看到的必定是一行中最右边的结点,从这个角度来说,肯定是层序遍历的最后
一个结点。
问题转化为如何求二叉树中每一层最后一个结点。
这个之前统计过,可以做size=1,nextSize=0,不断更新size和nextSize,当size减为0,这一层遍历结束
当前的结点即为这一层最后一个结点

输入:
7
1 2 3 N 5 N 4
输出:
1 3 4
*/

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)
		{
			return result;
		}
		queue<TreeNode*> nodes;
		nodes.push(root);
		int size = 1;
		int nextSize = 0;
		TreeNode* node;
		while(!nodes.empty())
		{
			node = nodes.front();
			nodes.pop();
			if(!node)
			{
				continue;
			}
			if(node->left)
			{
				nodes.push(node->left);
				nextSize++;
			}
			if(node->right)
			{
				nodes.push(node->right);
				nextSize++;
			}
			size--;
			//当前这一层遍历结束,当前结点即为这一层最右边的结点
			if(0 == size)
			{
				result.push_back(node->val);
				size = nextSize;
				nextSize = 0;
			}
		}
		return result;
    }
};

void print(vector<int>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	for(int i = 0 ; i < size ; i++)
	{
		cout << result.at(i) << " " ;
	}
	cout << endl;
}

//构建二叉树,这里默认首个元素为二叉树根节点,然后接下来按照作为每个结点的左右孩子的顺序遍历
//这里的输入是每个结点值为字符串,如果字符串的值为NULL表示当前结点为空
TreeNode* buildBinaryTree(vector<string>& nums)
{
	if(nums.empty())
	{
		return NULL;
	}
	int size = nums.size();
	int j = 0;
	//结点i的孩子结点是2i,2i+1
	vector<TreeNode*> nodes;
	int value;
	for(int i = 0 ; i < size ; i++)
	{
		//如果当前结点为空结点,自然其没有左右孩子结点
		if("N" == nums.at(i))
		{
			nodes.push_back(NULL);
			continue;
		}
		value = atoi(nums.at(i).c_str());
		TreeNode* node = new TreeNode(value);
		nodes.push_back(node);
	}
	//设定孩子结点指向,各个结点都设置好了,如果但钱为空结点,就不进行指向
	for(int i = 1 ; i <= size ; i++)
	{
		if(NULL == nodes.at(i-1))
		{
			continue;
		}
		if(2 * i <= size)
		{
			nodes.at(i-1)->left = nodes.at(2*i - 1);
		}
		if(2*i + 1 <= size)
		{
			nodes.at(i-1)->right = nodes.at(2*i);
		}
	}
	//设定完了之后,返回根节点
	return nodes.at(0);
}

void deleteBinaryTree(TreeNode* root)
{
	if(!root)
	{
		return;
	}
	if(NULL == root->left && NULL == root->right)
	{
		delete root;
		root = NULL;
	}
	if(root)
	{
		deleteBinaryTree(root->left);
		deleteBinaryTree(root->right);
	}
}

void print(vector<vector<string>>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	int len;
	for(int i = 0 ; i < size ; i++)
	{
		len = result.at(i).size();
		for(int j = 0 ; j < len ; j++)
		{
			cout << result.at(i).at(j) << " " ;
		}
		cout << endl;
	}
	cout << endl;
}

void process()
{
	 vector<string> nums;
	 string value;
	 int num;
	 Solution solution;
	 vector<int > result;
	 while(cin >> num )
	 {
		 nums.clear();
		 for(int i = 0 ; i < num ; i++)
		 {
			 cin >> value;
			 nums.push_back(value);
		 }
		 TreeNode* root = buildBinaryTree(nums);
		 result = solution.rightSideView(root);
		 print(result);
		 deleteBinaryTree(root);
	 }
}


int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


class BinaryTree: def init(self, rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self, newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getLeftChild(self): return self.leftChild def getRightChild(self): return self.rightChild def setRootVal(self, obj): self.key = obj def getRootVal(self): return self.key def buildParseTree(fpexp): fplist = list(fpexp) pStack = [] eTree = BinaryTree('') pStack.append(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.append(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+','-','','/',')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+','-','','/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.append(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree def preorder(tree): if tree: print(tree.getRootVal()) preorder(tree.getLeftChild()) preorder(tree.getRightChild()) def inorder(tree): if tree!=None: inorder(tree.getLeftChild()) print(tree.getRootVal()) inorder(tree.getRightchild()) def postorder(tree): if tree!=None: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print(tree.getRootVal()) import operator def evaluate(parseTree): opers = {'+': operator.add,'-': operator.sub,'*': operator.mul,'/': operator.truediv} leftC = parseTree.getLeftChild() rightC = parseTree.getRightChild() if leftC and rightC: fn = opers[parseTree.getRootVal()] return fn(evaluate(leftC), evaluate(rightC)) else: return parseTree.getRootVal() # 测试案例 pt=buildParseTree('((10+5)*3)') print("先序遍历:") preorder(pt) print("中序遍历:") inorder(pt) print("后序遍历:") postorder(pt) print("求值结果:", evaluate(pt))有什么问题吗,如果有请帮我改错
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值