题目链接:点击打开链接
本题为非递归实现中序遍历。Java 参考代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<Integer> list;
public Solution() {
list = new LinkedList<Integer>();
}
// 非递归中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null){
return list;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while(current!= null || !stack.isEmpty()){
if(current != null){
stack.push(current);
current =current.left;
} else{
current = stack.pop();
list.add(current.val);
current = current.right;
}
}
return list;
}
}
我在做这道题目的时候,比较纠结的是如何使用给定的数组构建出对应的二叉树,以进行本地测试。思路是使用队列保存每一个节点。下面给出本地测试时的完整代码:
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
private TreeNode root;
private List<Integer> list;
public Solution() {
root = null;
list = new LinkedList<Integer>();
}
// 利用输入的数组构造一颗二叉树(使用队列)
public void buildTree(Integer[] nums){
if(nums[0]==null){
return;
}
if(root == null){
root = new TreeNode(nums[0]);
}
Queue<TreeNode>queue = new LinkedList<TreeNode>();
queue.add(root);
TreeNode current = null;
boolean left = true;
for(int i=1; i<nums.length; i++){
if(!queue.isEmpty()){
current = queue.peek();
if(current != null){
if(left){
if(nums[i] == null)
current.left = null;
else
current.left = new TreeNode(nums[i]);
queue.add(current.left);
left = false;
} else {
if(nums[i] == null)
current.right = null;
else {
current.right = new TreeNode(nums[i]);
}
queue.remove();
queue.add(current.right);
left = true;
}
} else {
queue.remove();
i--;
}
}
}
}
// 非递归中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null){
return list;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while(current!= null || !stack.isEmpty()){
if(current != null){
stack.push(current);
current =current.left;
} else{
current = stack.pop();
list.add(current.val);
current = current.right;
}
}
return list;
}
public static void main(String[] args) {
Integer[] nums = {1,2,3,null, 4, 5, null, null, null, null, null};
Solution solution = new Solution();
// 构造数组对应的二叉树
solution.buildTree(nums);
// 非递归中序排列
List<Integer> list = solution.inorderTraversal(solution.root);
for(Integer integer: list){
System.out.print(integer + " ");
}
}
}