题目描述
Given a binary tree, return the inorder traversal of its nodes' values.
样例
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
思路分析
递归法:按照中序遍历的定义,即“左 根 右”的进行递归即可
循环法:利用栈“先进后出”的特点,从根节点开始,使左节点依次进栈,进栈完毕,开始添加到list,先添加左节点,父节点即此子树的“根”,再使右节点进栈即可完成子树的中序遍历,通过循环,逐步完成对整个树的中序遍历
代码
方法一:递归
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
inorderTraversal(root, list); //进入递归
return list;
}
public void inorderTraversal(TreeNode root,List<Integer> list){
if (root != null) {
if (root.left != null) { //先遍历左节点
inorderTraversal(root.left,list);
}
list.add(root.val); //再遍历根节点
if (root.right != null) { //最后遍历右节点
inorderTraversal(root.right,list);
}
}
}
结果
方法二:循环
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode temp = root;
while (temp!=null || !stack.isEmpty()) {
while (temp != null) { //通过循环 遍历左节点到树的最底层左节点
stack.push(temp);
temp = temp.left;
}
temp = stack.pop(); //左节点出栈 temp为空时根节点出栈
list.add(temp.val);
temp = temp.right; //右节点遍历
}
return list;
}