您的位置:首页 > 其它

Sum Root to Leaf Numbers

2015-11-01 14:08 330 查看
题目名称

Sum Root to Leaf Numbers—这里写链接内容

描述

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

1
/ \
2   3


The root-to-leaf path 1->2 represents the number 12.

The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

分析

  DFS,vector存储一条路径上的所有节点,set存储已经访问的节点,当访问的节点是叶子节点时,计算这条路径的Root to Leaf Numbers,然后加到sum中;当访问的节点是叶子节点或者该节点的左右孩子都已经访问时,退出vector中最后一个元素,回溯。

C++代码

/**************************************************************

Copyright:武汉大学计算机学院B507

Author: Ryan

Date:2015-10-29

Description:Sum Root to Leaf Numbers

**************************************************************/
#include<iostream>
#include<vector>
#include<set>
using namespace std;

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

int sumNumbers(TreeNode* root) {
if(!root)
return 0;
set<TreeNode*> visited;
vector<TreeNode*> node;
TreeNode* cur=root;
int sum=0;
node.push_back(cur);
while(!node.empty()) {
bool vLeft = visited.find(cur->left)!=visited.end();
bool vRight = visited.find(cur->right)!=visited.end();
//存在左孩子,并且左孩子没有被访问
if(cur->left && !vLeft){
node.push_back(cur->left);
visited.insert(cur->left);
cur = cur->left;
}
//存在右孩子,并且右孩子没有被访问
else if(cur->right && !vRight){
node.push_back(cur->right);
visited.insert(cur->right);
cur = cur->right;
}
//访问的是叶子节点
else if(!cur->left && !cur->right) {
int path=0;
for(int j=0;j<node.size();j++){
path = path*10+node[j]->val;
}
sum+=path;
node.pop_back();
cur=node.back();
}
//当前节点的左右孩子都已经被访问,则退出最后一个元素,回溯
else{
node.pop_back();
cur=node.back();
}
}
return sum;
}

int main() {
TreeNode *root = new TreeNode(1);
TreeNode *left = new TreeNode(2);
TreeNode *right = new TreeNode(3);
root->left = left;
root->right = right;
left->left=NULL;
left->right=NULL;
right->left=NULL;
right->right=NULL;
cout<<"Sum Root to Leaf Numbers is:"<<sumNumbers(root)<<endl;
delete(root);
delete(left);
delete(right);
return 0;
}


总结

  一开始不会写DFS的代码,回去看了书之后,自己写出来的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: