Java实现Leetcode题(二叉树)

Leetcode144(前序遍历)

	//递归
    public static List inorderTraversal(TreeNode root){
		List list = new ArrayList<>();
		inorder(root,list);
		return list;
	}
	public static void inorder(TreeNode root,List list) {
		if(root==null) {
			return;
		}
		list.add(root.val);
		inorder(root.left,list);
		inorder(root.right,list);
	}
    
    //迭代
    public static List preorderTraversal(TreeNode root){
		List list = new ArrayList();
		Deque de = new LinkedList<>();
		if(root==null) {
			return list;
		}
		de.addFirst(root);
		while(!de.isEmpty()) {
			TreeNode temp = de.peekFirst();
			de.pollFirst();
			list.add(temp.val);
			if(temp.right!=null) {
				de.addFirst(temp.right);
			}
			if(temp.left!=null) {
				de.addFirst(temp.left);
			}
		}
		return list;
	}

Leetcode145(后序遍历) 

//迭代法
public static List postorderTraversal(TreeNode root){
		List list = new ArrayList<>();
		Deque de = new LinkedList<>();
		if(root==null) {
			return list;
		}
		de.addFirst(root);
		while(!de.isEmpty()) {
			TreeNode temp = de.peekFirst();
			de.pollFirst();
			list.add(temp.val);
			if(temp.left!=null) {
				de.addFirst(temp.left);
			}
			if(temp.right!=null) {
				de.addFirst(temp.right);
			}
		}
		Collections.reverse(list);
		return list;
	}

   //递归
    public static List postorderTraversal(TreeNode root){
		List list = new ArrayList<>();
		postorder(root,list);
		return list;
	}
	public static void postorder(TreeNode root,List list) {
		postorder(root.left,list);
		postorder(root.right,list);
		list.add(root.val);
	}

Leetcode94(中序遍历)

//迭代
public static List inorderTraversal(TreeNode root){
		List list = new ArrayList<>();
		Deque de = new LinkedList<>();
		if(root == null) {
			return list;
		}
		TreeNode cur = root;
		while(cur!=null||!de.isEmpty()) {
			if(cur!=null) {
				de.addFirst(cur);
				cur = cur.left;
			}else {
				cur = de.peekFirst();
				list.add(cur.val);
				de.pollFirst();
				cur = cur.right;
			}
		}
		return list;
	}
    //递归
    public static List inorderTraveral(TreeNode root){
		List list = new ArrayList<>();
		inorder(root,list);
		return list;	
	}
	
	public static void inorder(TreeNode root,Listlist) {
		if(root==null) {
			return;
		}
		inorder(root.left,list);
		list.add(root.val);
		inorder(root.right,list);
	}
    


 

你可能感兴趣的:(数据结构,java,leetcode,linux)