二叉树的层序遍历
使用一个队列来访问即可,注意每一层的元素个数可以在一开始访问该层的时候,用队列里面的元素个数来表示出来
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res =new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
if (root!=null) queue.add(root);
while (!queue.isEmpty()){
int size=queue.size();
List<Integer> tem=new ArrayList<>();
for (int i=0;i<size;i++){
TreeNode t=queue.poll();
tem.add(t.val);
if (t.left!=null) queue.add(t.left);
if (t.right!=null) queue.add(t.right);
}
res.add(tem);
}
return res;
}
}
二叉树的统一递归法
写递归的步骤:
- 先确定递归函数要用到的参数已经返回类型
- 确定递归终止条件
- 确定每一次递归函数里的处理逻辑
//以前序遍历为例,其他两个改一下顺序就好了
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
}
二叉树的统一迭代遍历
这里采用的是标记法,依旧是用栈这种数据结构。
访问一个元素,依次再向栈里压入它的字节点和它本身这个节点(按照想要的访问顺序)。
由于它本身这个节点是已经被访问过了,所以做一个标记,在它后面插入一个null节点,这样就知道哪些是已经访问过的,哪些是还没有访问过的节点。
访问过的节点就直接加入数组输出。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
Deque<TreeNode> stack=new LinkedList<>();
if(root!=null) stack.push(root);
while (!stack.isEmpty()){
TreeNode top=stack.pollLast();
if (top!=null){
if (top.right!=null) stack.addLast(top.right);
stack.addLast(top);
stack.addLast(null);
if (top.left!=null) stack.addLast(top.left);
}else {
TreeNode st=stack.pollLast();
res.add(st.val);
}
}
return res;
}}