二叉树的中序遍历
二叉树的中序遍历
一、给定一个二叉树root,返回它的中序遍历。
实例

输入:root = [1,null,2,3]
输出:[1,3,2]
二、题目分析
这里的二叉树的中序遍历就是,左,中,右的来遍历这个数。从这个树的最深处的左子叶开始遍历。按照左,中,右遍历。这是一个天然的递归。
三、解题思路
方法1
采用递归的方式,一直找到最左边的节点。将值依次存入数组中。
代码实现
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Inorder(root,list);
return list;
}
public void Inorder(TreeNode root , List list){
if(root == null){
return;
}
Inorder(root.left,list);
list.add(root.val);
Inorder(root.right,list);
}
}
方法二
迭代思想,和递归是差不多的,只是递归隐藏了操作栈,而迭代,显示了栈的操作。
代码实现
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Deque<TreeNode> sta = new LinkedList<TreeNode>();
while(root != null || !sta.isEmpty()){
while(root != null){
sta.push(root);
root = root.left;
}
root = sta.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}
浙公网安备 33010602011771号