0
点赞
收藏
分享

微信扫一扫

CentOS快速配置网络&&Docker快速部署

目录

验证栈序列(medium)

题目解析

讲解算法原理

编写代码

N叉树的层序遍历(medium)

题目解析

讲解算法原理

编写代码


验证栈序列(medium)

题目解析

1.题目链接:. - 力扣(LeetCode)

2.题目描述

讲解算法原理

解法(栈):
算法思路:

⽤栈来模拟进出栈的流程。
⼀直让元素进栈,进栈的同时判断是否需要出栈。当所有元素模拟完毕之后,如果栈中还有元素,那么就是⼀个⾮法的序列。否则,就是⼀个合法的序列。

编写代码

c++算法代码:

class Solution
{
public:
 bool validateStackSequences(vector<int>& pushed, vector<int>& popped) 
 {
 stack<int> st;
 int i = 0, n = popped.size();
 for(auto x : pushed)
 {
 st.push(x);
 while(st.size() && st.top() == popped[i])
 {
 st.pop();
 i++;
 }
 }
 return i == n;
 }
};

java算法代码:

class Solution
{
 public boolean validateStackSequences(int[] pushed, int[] popped) 
 {
 Stack<Integer> st = new Stack<>();
 int i = 0, n = popped.length;
 for(int x : pushed)
 {
 st.push(x);
 while(!st.isEmpty() && st.peek() == popped[i])
 {
 st.pop();
 i++;
 }
 }
 return i == n;
 }
}

N叉树的层序遍历(medium)

题目解析

1.题目链接:. - 力扣(LeetCode)

2.题目描述

讲解算法原理

解法:
算法思路:

层序遍历即可~
仅需多加⼀个变量,⽤来记录每⼀层结点的个数就好了。

编写代码

c++算法代码:

/*
// Definition for a Node.
class Node {
public:
 int val;
 vector<Node*> children;
 Node() {}
 Node(int _val) {
 val = _val;
 }
 Node(int _val, vector<Node*> _children) {
 val = _val;
 children = _children;
 }
};
*/
class Solution
{
public:
 vector<vector<int>> levelOrder(Node* root) 
 {
 vector<vector<int>> ret; // 记录最终结果 queue<Node*> q; // 层序遍历需要的队列
 if(root == nullptr) return ret;
 q.push(root);
 while(q.size())
 {
 int sz = q.size(); // 先求出本层元素的个数 vector<int> tmp; // 统计本层的节点
 for(int i = 0; i < sz; i++)
 {
 Node* t = q.front();
 q.pop();
 tmp.push_back(t->val); 
 for(Node* child : t->children) // 让下⼀层结点⼊队 {
 if(child != nullptr)
 q.push(child);
 }
 }
 ret.push_back(tmp);
 }
 return ret;
 }
};

java算法代码:

/*
// Definition for a Node.
class Node {
 public int val;
 public List<Node> children;
 public Node() {}
 public Node(int _val) {
 val = _val;
 }
 public Node(int _val, List<Node> _children) {
 val = _val;
 children = _children;
 }
};
*/
class Solution
{
 public List<List<Integer>> levelOrder(Node root) 
 {
 List<List<Integer>> ret = new ArrayList<>();
 if(root == null) return ret;
 Queue<Node> q = new LinkedList<>();
 q.add(root);
 while(!q.isEmpty())
 {
 int sz = q.size();
 List<Integer> tmp = new ArrayList<>(); // 统计本层的结点信息 for(int i = 0; i < sz; i++)
 {
 Node t = q.poll();
 tmp.add(t.val);
 for(Node child : t.children) // 让孩⼦⼊队 {
 if(child != null)
 q.add(child);
 }
 }
 ret.add(tmp);
 }
 return ret;
 }
}
举报

相关推荐

0 条评论