题目
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
解法思路(一)
- 借助栈;
- 借助辅助类
Command
;
关于辅助类 Command
- 包装了
TreeNode
和命令; - 命令有两种:
go
和print
; -
go
的话要把当前节点的左右孩子入栈; -
print
的话要就是遍历到这个节点了,要把该节点放入遍历的结果集;
关于栈的作用
- 中序遍历是这样的:先遍历左子树,再遍历根,最后遍历右子树;
- 因为栈有这样的特点:先入栈的后出栈,所以最先要遍历的节点最后入栈,最后要遍历的节点最先入栈;
- 栈有点像一个备忘录,越后面要做的事情,越先放进栈中,这样只需一个个拿出栈顶的事情做,就不会忘记最早要干的事情;
- 于遍历来说,之后要遍历的节点因之前被放进栈中而被记起;
解法实现(一)
时间复杂度
- O(n),n为树的节点个数;
空间复杂度
O(h),h为树的高度,因为前序遍历属于深度优先遍历,所以栈的深度最深为 h;
关键字
中序遍历
非递归
栈
辅助类 Command
实现细节
package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution94_1 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
private class Command {
public String c;
public TreeNode treeNode;
public Command(String c, TreeNode treeNode) {
this.c = c;
this.treeNode = treeNode;
}
}
public List inorderTraversal(TreeNode root) {
List res = new ArrayList<>();
if (root == null) {
return res;
}
Stack stack = new Stack<>();
Command command = new Command("go", root);
stack.push(command);
while (!stack.isEmpty()) {
command = stack.pop();
if (command.c.equals("print")) {
res.add(command.treeNode.val);
} else {
if (command.treeNode.right != null) {
stack.push(new Command("go", command.treeNode.right));
}
stack.push(new Command("print", command.treeNode));
if (command.treeNode.left != null) {
stack.push(new Command("go", command.treeNode.left));
}
}
}
return res;
}
}
返回 LeetCode [Java] 目录