数据结构和算法:18.leetcode刷题-数字和位运算、树

1. 数字篇

  1. 两数之和-1
  2. 整数反转-7

2. 位运算

  1. 两数相加-2
  2. 2的幂-231
  3. 3的幂-326
  4. 位1的个数-191
  5. 阶乘后的零-172

3. 树

  1. 二叉树的中序遍历-94

递归方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void inorderTraversal(TreeNode* root, vector<int>* res){
if(root == NULL){
return;
}
// 访问
inorderTraversal(root->left,res);
// 打印
res->push_back(root->val);
inorderTraversal(root->right,res);
}

vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorderTraversal(root,&res);
return res;
}

非递归方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TraversalOperate> operates = new Stack<>();
List<Integer> res = new ArrayList<>();

operates.push(new TraversalOperate(1,root));

while(!operates.isEmpty()){
TraversalOperate top = operates.pop();

if(top.root == null)
continue;

if(top.operate == 0)
res.add(top.root.val);
else{
// 从下往上看
operates.add(new TraversalOperate(1,top.root.right));
operates.add(new TraversalOperate(0,top.root));
operates.add(new TraversalOperate(1,top.root.left));
}
}
return res;
}

class TraversalOperate{
int operate; // 0 print 1 visit
TreeNode root; // 节点
public TraversalOperate(int operate,TreeNode root){
this.operate = operate;
this.root = root;
}
}
}

几个题

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%