二叉树前序遍历
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;
}