1. 二叉树的最短路径
1.1 题目描述
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node…
1.2 广度优先搜索(层次遍历)
- 题目要找的是最短路径,找到一个叶子结点,并且保证该叶子结点距离根结点的距离最近。
- 拿到这道题的第一想法,就是层次遍历,一层一层遍历,直到发现第一个叶子结点,并在其中记录depth。
- 树中的层次遍历,其实就是图的广度优先搜索,不过这里需要注意的是,depth只能是根据层数进行递增,而不能根据结点进行递增。所以我们要在广度优先搜索中再加一层循环——即对于结点我们要一层一层的push进queue,再一层一层的pop出queue。
class Solution {
public:
int run(TreeNode *root) {
if(root==NULL)
return 0;
if(root->left==NULL && (root->right==NULL))
return 1;
queue<TreeNode*> q;
q.push(root);
TreeNode* temp;
int depth = 0;
while(!q.empty())
{
++depth;
int size = q.size();
for(int i = 0;i<size;i++)
{
temp = q.front();
q.pop();
if(temp->left==NULL &&(temp->right==NULL))
return depth;
if(temp->left!=NULL)
q.push(temp->left);
if(temp->right!=NULL)
q.push(temp->right);
}
}
return depth;
}
};
1.3 使用递归获得树深的方法
- 之前我们在求树的深度时,会使用递归的方法,
int getDepth(TreeNode* root)
{
if(root==NULL)
return 0;
int left = getDepth(root->left);
int right = getDepth(root->right);
return left>right?(left+1):(right+1);
}
-
这道题也很容易想到这个方法,不过是我们要取left和right中比较小的值。
-
不过这样做是有坑的,因为不像是单独的求深度,我们要确保求得的深度是有对应的叶子节点的,比如{1,2},如果只是需要小的值,很容易得到depth=1的结果,但是2才是叶子结点,所以正确答案应该是2.
class Solution {
public:
int run(TreeNode *root) {
if(root==NULL)
return 0;
int depth = getDepth(root);
return depth;
}
int getDepth(TreeNode* root)
{
if(root->left==NULL &&(root->right==NULL))
return 1;
int left = INT_MAX,right=INT_MAX;
if(root->left!=NULL)
left = getDepth(root->left)+1;
if(root->right!=NULL)
right = getDepth(root->right)+1;
return left<right?left:right;
}
};
2.逆波兰式的计算
2.1 题目描述
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
2.2 借用栈进行
- 这道题没什么好说的,题目要求比较简单,不需要考虑什么异常情况,遇到值入栈,遇到符号就弹出两个值进行计算,再将结果入栈,这样最后栈中会存储最终的结果。
- 只需要写入栈出栈的逻辑,以及string转int的逻辑,要考虑正负号。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> tokenStack;
int a;
int b;
for(auto token: tokens)
{
if(token=="+")
{
a = tokenStack.top();
tokenStack.pop();
b = tokenStack.top();
tokenStack.pop();
tokenStack.push(a+b);
}
else if(token=="-")
{
a = tokenStack.top();
tokenStack.pop();
b = tokenStack.top();
tokenStack.pop();
tokenStack.push(b-a);
}
else if(token=="*")
{
a = tokenStack.top();
tokenStack.pop();
b = tokenStack.top();
tokenStack.pop();
tokenStack.push(a*b);
}
else if(token=="/")
{
a = tokenStack.top();
tokenStack.pop();
b = tokenStack.top();
tokenStack.pop();
tokenStack.push(int(b/a));
}
else
tokenStack.push(string2int(token));
}
return tokenStack.top();
}
int string2int(string s)
{
int num = 0;
bool flag = false;
int base = 0;
if(s[0]=='+')
base += 1;
else if(s[0]=='-')
{
base +=1;
flag = true;
}
for(int i =base;i<s.size();i++)
{
char c = s[i];
num = num*10+c-'0';
}
if(flag)
num = -num;
return num;
}
};