二叉樹前序,後序,中序遍歷以及驗證二叉樹

二叉樹前序遍歷

在這裏插入圖片描述

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;
}
二叉樹後序遍歷

在這裏插入圖片描述

public List<Integer> postorderTraversal(TreeNode root) {
	LinkedList<TreeNode> stack = new LinkedList<>();
	LinkedList<Integer> output = new LinkedList<>();
	if (null == root) {return output;}
	stack.add(root);
	while (!stack.isEmpty()) {
		// 從頭取
		TreeNode node = stack.pollLast();
		// 輸出頭
		output.addFirst(node.val);
		// 左
		if (node.left != null) {
			stack.add(node.left);
		}
		// 右
		if (node.right 1!= null) {
			stack.add(node.right);
		}
	}
	return output;
}
二叉樹中序遍歷

在這裏插入圖片描述

public List<Integer> inorderTraversal(TreeNode root) {
	List<Integer> res = new LinkedList<>();
	Stack<TreeNode> stack = new Stack<>();
	TreeNode curr = root;
	// loop未壓或者有未彈數據 
	while (!stack.isEmpty() || curr != null) {
		// 壓左
		while (curr != null) {
			stack.push(curr);
			curr = curr.left;
		}
		// 彈一個
		curr = stack.pop();
		res.add(curr.val);
		// 轉方向
		curr = curr.right;
	}
	return res;
}
驗證二叉樹的有效性

在這裏插入圖片描述
在這裏插入圖片描述

方法一:遞歸
public boolean isValidBST(TreeNode root) {
	return helper(root, null, null);
}

public boolean helper(TreeNode node, Integer lower, Integer upper) {
	// terminator
	if (node == null) return true;
	// process current logic 
	// 如果當前值越界,則當前方法棧返回false, 且不用繼續深搜子樹
	int value = node.val;
	if (lower != null && value <= lower) return false;
	if (upper != null && value >= upper) return false;

	// drill down
	if (!helper(node.right, value, upper)) return false;
	if (!helper(node.left, lower, value)) return false;
	
	// restore current status
	// 無
	return true;; // 當前層有效,並且左右子樹有效
}
方法一:迭代
public boolean isValidBST(TreeNode root) {
	if (null == root) return true;
	Integer inorder = null;
	Stack<TreeNode> stack = new Stack<>();
	TreeNode curr = root;
	while (!stack.isEmpty() || curr != null) {
	 // 迭代左子樹入棧
		while (curr != null) {
			stack.push(curr);
			curr = curr.left;
		}
		curr = stack.pop();
		if (inorder != null && inorder >= curr.val) return false;
		inorder = curr.val;
		// 迭代右子樹入棧
		curr = curr.right;
	}
	return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章