递归法
与先序、后序只有顺序的区别哈哈
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, res);
return res;
}
public void dfs(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
dfs(root.left, res);
res.add(root.val);
dfs(root.right, res);
}
}
迭代法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> s = new Stack<>();
while (!s.empty() || root != null) {
while (root != null) {
s.push(root);
root = root.left;
}
root = s.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
通用的迭代方法
通用的迭代方法,只用交换入栈的顺序就可以实现不同的顺序遍历,感觉这个是利用了,每个叶子节点也是两个空指针的父节点,父节点后面插入null节点,到能弹出父节点的时候,说明前面该遍历的都走完了。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> s = new Stack<>();
s.push(root);
while (!s.empty()) {
TreeNode cur = s.pop();
if (cur != null) {
if (cur.right != null) {
s.push(cur.right);
}
s.push(cur);
s.push(null);
if (cur.left != null) {
s.push(cur.left);
}
} else {
TreeNode h = s.pop();
res.add(h.val);
}
}
return res;
}
}