二叉树的定义类:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
层次遍历
使用queue存储每一层的节点。记录每一层的size,遍历记录数值
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//迭代
List<List<Integer>> result = new ArrayList<>();
if(root == null) return result;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
int level = 1;
while(!queue.isEmpty()){
int levelSize = queue.size();
List<Integer> list = new ArrayList<>();
for(int i =0;i<levelSize;i++){
TreeNode currNode = queue.poll();
list.add(currNode.val);
if(currNode.left!=null){
queue.add(currNode.left);
}
if(currNode.right != null){
queue.add(currNode.right);
}
}
level++;
result.add(list);
}
return result;
}
}
二叉树中序遍历
递归:顺序,左右根
迭代:用栈,再用一个指针模拟访问过程
递归:
class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
helper(root, res);
return res;
}
public void helper(TreeNode root, List < Integer > res) {
if (root != null) {
if (root.left != null) {
helper(root.left, res);
}
res.add(root.val);
if (root.right != null) {
helper(root.right, res);
}
}
}
}
迭代:
public class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
Stack < TreeNode > stack = new Stack < > ();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}
二叉树的前序遍历 leetcode144
递归:就是依次输出根,左,右,递归下去
迭代:使用栈来完成,我们先将根节点放入栈中,然后将其弹出,依次将该弹出的节点的右节点,和左节点,**注意顺序,**是右,左,为什么?因为栈是先入后出的,我们要先输出右节点,所以让它先进栈.
递归:
public void helper(List<Integer> list,TreeNode root){
if(root == null){
return;
}
list.add(root.val);
helper(list,root.left);
helper(list,root.right);
}
迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
if (root == null) {
return output;
}
stack.add(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pollLast();
output.add(node.val);
if (node.right != null) {
stack.add(node.right);
}
if (node.left != null) {
stack.add(node.left);
}
}
return output;
}
}
145. 二叉树的后序遍历
递归:同理,顺序:左,右,根
public void helper(List<Integer> list,TreeNode root){
if(root == null){
return;
}
helper(list,root.left);
helper(list,root.right);
list.add(root.val);
}
迭代:这就很上面的先序一样,我们可以改变入栈的顺序,刚才先序是从右到左,我们这次从左到右,最后得到的结果取逆.
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
list.add(temp.val);
if(temp.left != null){
stack.push(temp.left);
}
if(temp.right != null){
stack.push(temp.right);
}
}
Collections.reverse(list);
return list;
}
}