leetcode解题: Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

Show Company Tags
Show Tags
Show Similar Problems

解法1: Recursion

用递归的in-order很简单,按字面理解就是先左再自己再右。
C++

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
helper(root, res);
return res;
}
void helper(TreeNode* root, vector<int>& res) {
if (!root) {
return;
}
helper(root->left, res);
res.push_back(root->val);
helper(root->right, res);
}
};

Java

1

解法2: Iterative

主要考虑的就是用一个stack来存储还没有访问的节点, 难点在于确定什么时候push和pop。
那么在寻找最小值的时候,一路上碰到的所有node都push
如果碰到了空节点,则证明现在的这条路已经到底了,需要往回寻找,这个时候就可以pop了,记录节点的数值。并且把将要探寻的指针放到right上继续。
C++

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
stack<TreeNode*> store;
TreeNode* cur = root;
while (cur || !store.empty()) {
if (cur) {
store.push(cur);
cur = cur->left;
} else {
TreeNode* temp = store.top();
res.push_back(temp->val);
store.pop();
cur = temp->right;
}
}
return res;
}
};

Java

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<TreeNode> stack = new Stack<>();
while (root!= null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode temp = stack.pop();
res.add(temp.val);
root = temp.right;
}
}
return res;
}
}