树的深度遍历、广度遍历、前中后序遍历

  • 借助栈进行深度优先遍历
public class TreeNode {
	public int val;
	public TreeNode left;
	public TreeNode right;

	public TreeNode() {
	}

	public TreeNode(int val) {
		this.val = val;
	}

	public TreeNode(int val, TreeNode left, TreeNode right) {
		this.val = val;
		this.left = left;
		this.right = right;
	}
}

public static List<Integer> deep(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		Stack<TreeNode> stack = new Stack<TreeNode>();
		if (root != null) {
			stack.push(root);
			while (true) {
				if (stack.size() != 0) {
					TreeNode pop = stack.pop();
					list.add(pop.val);
					if (pop.right != null) {
						stack.push(pop.right);
					}
					if (pop.left != null) {
						stack.push(pop.left);
					}

				} else {
					break;
				}

			}

		}
		return list;
	}
  • 借助队进行广度优先遍历
public static List<Integer> broad(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		if (root != null) {
			queue.add(root);
			while (!queue.isEmpty()) {
				TreeNode poll = queue.poll();
				list.add(poll.val);
				if (poll.left != null) {
					queue.add(poll.left);
				}
				if (poll.right != null) {
					queue.add(poll.right);
				}
			}
		}

		return list;

	}
  • 借助递归进行前中后序遍历
  • 中序
public List<Integer> in(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        inBl(list,root);
        return list;
    }
    public void inBl(List<Integer> list,TreeNode root){
        if(root==null)
            return;
        if(root.left!=null)
        	inBl(list,root.left);
        if(root!=null)
            list.add(root.val);
        if(root.right!=null)
        	inBl(list,root.right);
    }
  • 前序
public List<Integer> bef(TreeNode root){
		List<Integer> list=new ArrayList<Integer>();
		befBl(list,root);
    	return list;
    }
    public void befBl(List<Integer> list,TreeNode root) {
    	if (root==null) {
			return;
		}
    	
    	if (root!=null) {
			list.add(root.val);
		}
    	if (root.left!=null) {
			befBl(list, root.left);
		}
    	if (root.right!=null) {
			befBl(list, root.right);
		}
    }
  • 后序
public List<Integer> after(TreeNode root) {
    	List<Integer> list=new ArrayList<>();
        aftBl(list,root);
        return list;
	}
    public void aftBl(List<Integer> list,TreeNode root) {
    	if (root==null) {
			return;
		}
    	if (root.left!=null) {
			aftBl(list, root.left);
		}
    	if (root.right!=null) {
			aftBl(list, root.right);
		}
    	if (root!=null) {
			list.add(root.val);
		}
    }