层次遍历
//层次
public int[] levelOrder(TreeNode root) {
if(root==null) return new int[0];
List<Integer> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
//TreeNode node = root;
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
int [] res = new int [list.size()];
for(int i=0;i<res.length;i++){
res[i]=list.get(i);
}
return res;
}
递归:先中后序遍历
public void preOrder(TreeNode root){
List<TreeNode> list = new ArrayList<>();
if(root==null) return;
list.add(root);
if(root.left!=null){
preOrder(root.left);
}
if(root.right!=null){
preOrder(root.right);
}
}
//递归 -中序
public void inOrder(TreeNode root){
List<TreeNode> list = new ArrayList<>();
if(root==null) return;
if(root.left!=null){
preOrder(root.left);
}
list.add(root);
if(root.right!=null){
preOrder(root.right);
}
}
//递归 -后续
public void postOrder(TreeNode root){
List<TreeNode> list = new ArrayList<>();
if(root==null) return;
if(root.left!=null){
preOrder(root.left);
}
if(root.right!=null){
preOrder(root.right);
}
list.add(root);
}
非递归:先中后序遍历
//非递归-先序
public void preOrder(TreeNode root){
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(root!=null||!que.isEmpty()){
//一直往二叉树的左子树上走
while(root!=null){
list.add(root.val);
stack.push(root);
root = root.left;
}
//左边的节点都走完了 改变节点方向
if(!stack.isEmpty()){
root = stack.pop();
root=root.right;
}
}
}
//非递归-中序
public void inOrder(TreeNode root){
List<Integer> list = new ArrayList<>();//结果
Stack<TreeNode> stack = new Stack<>();
while(root!=null||!que.isEmpty()){
一直向左,但是先不存入
while(root!=null){
stack.push(root);
root = root.left;
}
//左边的节点都走完了 存入list并 改变节点方向
if(!stack.isEmpty()){
root = stack.pop();
list.add(root.val);
root=root.right;
}
}
}
//非递归-后序
public void postOrder(TreeNode root){
List<Integer> list = new ArrayList<>();//结果
Stack<TreeNode> stack = new Stack<>();
while(root!=null||!que.isEmpty()){
//一直向右
while(root!=null){
list.add(root.val)
stack.push(root);
root = root.right;
}
if(!stack.isEmpty()){
root = stack.pop();
root=root.left;
}
}
}