leetcode -day29 Binary Tree Inorder Traversal & Restore IP Addresses
阿新 • • 發佈:2019-01-28
1、
,採用動態規劃的方法,引數num表示字串表示為第幾段,如果num==4則表示最後一段,直接判斷字串是否有效,並儲存結果即可,如果不是則點依次加在第0個、第1個....後面,繼續遞迴判斷後面的串。
Binary Tree Inorder Traversal
Given a binary tree, return theinordertraversal of its nodes' values.
For example:
Given binary tree{1,#,2,3}
,
1 \ 2 / 3
return[1,3,2]
.
Note:Recursive solution is trivial, could you do it iteratively?
分析:求二叉樹的中序遍歷,採用遞迴的方法的話非常簡單,如果非遞迴的話,就需要用棧來儲存上層結點,開始向左走一直走到最左葉子結點,然後將此值輸出,從佇列中彈出,如果右子樹不為空則壓入該彈出結點的右孩子,再重複上面往左走的步驟直到棧為空即可。
class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> result; if(!root){ return result; } TreeNode* tempNode = root; stack<TreeNode*> nodeStack; while(tempNode){ nodeStack.push(tempNode); tempNode = tempNode->left; } while(!nodeStack.empty()){ tempNode = nodeStack.top(); nodeStack.pop(); result.push_back(tempNode->val); if(tempNode->right){ nodeStack.push(tempNode->right); tempNode = tempNode->right; while(tempNode->left){ nodeStack.push(tempNode->left); tempNode = tempNode->left; } } } return result; } };
2、Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given"25525511135"
,
return["255.255.11.135", "255.255.111.35"]
.
(Order does not matter)
分析:此題跟我之前遇到的一個判斷字串是否是ip地址有點類似,http://blog.csdn.net/kuaile123/article/details/21600189
如下:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result;
int len = s.length();
if(len < 4 || len > 12){
return result;
}
dfs(s,1,"",result);
return result;
}
void dfs(string s, int num, string ip, vector<string>& result){
int len = s.length();
if(num == 4 && isValidNumber(s)){
ip += s;
result.push_back(ip);
return;
}else if(num <= 3 && num >= 1){
for(int i=0; i<len-4+num && i<3; ++i){
string sub = s.substr(0,i+1);
if(isValidNumber(sub)){
dfs(s.substr(i+1),num+1,ip+sub+".",result);
}
}
}
}
bool isValidNumber(string s){
int len = s.length();
int num = 0;
for(int i=0; i<len; ++i){
if(s[i] >= '0' && s[i] <= '9'){
num = num*10 +s[i]-'0';
}else{
return false;
}
}
if(num>255){
return false;
}else{
//非零串首位不為0的判斷
int size = 1;
while(num = num/10){
++size;
}
if(size == len){
return true;
}else{
return false;
}
}
}
};