public class BinaryTree {
public static class Node {
public Node(int val) {
this.val = val;
}
public int val;
public Node left;
public Node right;
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
}
}
上述的代码转换为二叉树图形如下:
前序遍历、中序遍历、后序遍历
二叉树的遍历分为三种:
前序遍历:头、左、右, 1、2、4、5、3、6、7
中序遍历:左、头、右, 4、2、5、1、6、3、7
后续遍历:左、右、头, 4、5、2、6、7、3、1
这里的前序、后序、中序,针对的目标是头节点,头节点在最前面,就是前序。
使用Java代码实现三种遍历方式:
public static void pre(Node node) {
if (node == null) return;
System.out.print(node.val + " ");
pre(node.left);
pre(node.right);
}
public static void in(Node node) {
if (node == null) return;
in(node.left);
System.out.print(node.val + " ");
in(node.right);
}
public static void pos(Node node) {
if (node == null) return;
pos(node.left);
pos(node.right);
System.out.print(node.val + " ");
}
public boolean isValidBST(TreeNode root) {
return isBinarySearchTree(root).isBST;
}
private Info isBinarySearchTree(TreeNode node) {
if (node == null) {
return null;
}
Info leftInfo = isBinarySearchTree(node.left);
Info rightInfo = isBinarySearchTree(node.right);
int max = node.val;
int min = node.val;
boolean isBST = true;
if (leftInfo != null) {
max = Math.max(max, leftInfo.max);
min = Math.min(min, leftInfo.min);
isBST = leftInfo.isBST && (leftInfo.max < node.val);
}
if (rightInfo != null) {
max = Math.max(max, rightInfo.max);
min = Math.min(min, rightInfo.min);
isBST = isBST && rightInfo.isBST && (rightInfo.min > node.val);
}
return new Info(max, min, isBST);
}
static class Info {
public int max;
public int min;
public boolean isBST;
public Info(int max, int min, boolean isBST) {
this.max = max;
this.min = min;
this.isBST = isBST;
}
}
二叉树路径总和
对应Leetcode:https://leetcode.cn/problems/path-sum/
解法:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
return process(root, targetSum, 0);
}
public boolean process(TreeNode node, int targetSum, int sum) {
// 叶子节点
if (node.left == null && node.right == null) {
return targetSum == sum + node.val;
}
boolean result = false;
if (node.left != null) {
result |= process(node.left, targetSum, sum + node.val);
}
if (node.right != null) {
result |= process(node.right, targetSum, sum + node.val);
}
return result;
}
}