Category | Difficulty | Likes | Dislikes |
---|
algorithms | Medium (68.96%) | 339 | - |
Tags Companies
给定一个二叉树,返回它的*中序 *遍历。
示例:
1
2
3
4
5
6
7
8
| 输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
|
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Discussion | Solution
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
| struct Solution;
// @lc code=start
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
/// ## 解题思路
/// - 递归+深度遍历
pub fn inorder_traversal1(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
fn inorder_dfs(node: &Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
match node {
None => {}
Some(x) => {
inorder_dfs(&x.borrow().left, res);
res.push(x.borrow().val);
inorder_dfs(&x.borrow().right, res);
}
}
}
let mut res = vec![];
inorder_dfs(&root, &mut res);
res
}
/// - 栈
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
let mut pending_nodes = vec![];
let mut node = root;
loop {
// 将所有左子节点入栈
while let Some(n) = node {
node = n.borrow_mut().left.take();
pending_nodes.push(n);
}
// 弹出栈顶节点
if let Some(n) = pending_nodes.pop() {
// 处理当前节点
res.push(n.borrow().val);
//
node = n.borrow_mut().right.take();
} else {
break;
}
}
res
}
}
// @lc code=end
|
1
2
3
4
5
6
7
8
9
10
11
12
| class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
if root.left:
res += self.inorderTraversal(root.left)
res.append(root.val)
if root.right:
res += self.inorderTraversal(root.right)
return res
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
pending = [] #
cur = root
while True:
while cur: #pending current node if left exists
pending.append(cur)
cur = cur.left
if not pending:
return res
cur = pending.pop()
res.append(cur.val)
cur = cur.right
|