总结了一下二叉树前两种遍历方法,之后更新第三种
前序遍历代码
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();//存储节点结构体的
LinkedList<Integer> out = new LinkedList<>();//存储整数的
if (root == null) {
return out;
}
stack.add(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pollLast();//把临近栈门口的出去,这时候left和right不管是什么只要位置该出去了就出去了
output.add(node.val);//输出存储器
if (node.right != null) {
stack.add(node.right);
}//先逆序进到stack里面
if (node.left != null) {
stack.add(node.left);
}
}
return out;
}
}
结果
中序遍历代码
leetcode上面的官方代码,感觉十分优雅,写了一些注释,帮助大家理解。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
//中序遍历就是紧着左边的遍历完 就遍历根 最后再想着右边
List<Integer> res = new ArrayList<Integer>();
Deque<TreeNode> stack = new LinkedList<TreeNode>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root = root.left;//如果左子树没有就跳出循环pop自身节点
}
root = stack.pop();//下一次循环如果右子树没有就直接pop下一个
res.add(root.val);
root = root.right;
}
return res;
}
}