public static int maxDepth1(TreeNode root) {
return root==null?0:Math.max(maxDepth1(root.left),maxDepth1(root.right))+1;
}
public static int bfs(TreeNode root){
if (root==null){
return 0;
}
Deque<TreeNode> deque=new LinkedList<>();
deque.push(root);
int count=0;
while (!deque.isEmpty()){
int size=deque.size();
while (size-->0){
TreeNode cur=deque.pop();
if(cur.left !=null){
deque.addLast(cur.left);
}
if (cur.right !=null){
deque.addLast(cur.right);
}
}
count++;
}
return count;
}
public static int dfs(TreeNode root){
if (root ==null) {
return 0;
}
Stack<TreeNode> stack=new Stack<>();
Stack<Integer> level=new Stack<>();
stack.push(root);
level.push(1);
int max=0;
while (!stack.isEmpty()){
TreeNode cur=stack.pop();
int temp=level.pop();
max=Math.max(temp,max);
if(cur.left!=null){
stack.push(cur.left);
level.push(temp+1);
}
if(cur.right!=null){
stack.push(cur.right);
level.push(temp+1);
}
}
return max;
}
//验证二叉搜索树
public static boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (pre != null && root.val <= pre.val) {
return false;
}
//保存前一个访问的结点
pre = root;
root = root.right;
}
return true;
}
//对称二叉树
public static boolean isSymmetric(TreeNode root) {
if (root ==null){
return true;
}
return isSymmetricHelper(root.left,root.right);
}
public static boolean isSymmetricHelper(TreeNode left,TreeNode right){
if (left==null && right==null){
return true;
}
if(left ==null || right==null || left.val !=right.val){
return false;
}
return isSymmetricHelper(left.left,right.right) && isSymmetricHelper(left.right,right.left);
}
//二叉树的层序遍历
public static List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
Deque<TreeNode> deque=new LinkedList<>();
List<List<Integer>> listList=new ArrayList<>();
deque.add(root);
while (!deque.isEmpty()){
int levelNum=deque.size();
List<Integer> list=new ArrayList<>();
for (int i=0;i<levelNum;i++){
TreeNode cur=deque.poll();
list.add(cur.val);
if(cur.left!=null){
deque.add(cur.left);
}
if (cur.right!=null){
deque.add(cur.right);
}
}
listList.add(list);
}
return listList;
}
//将有序数组转换为二叉搜索树
public static TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0) {
return null;
}
return sortedArrayToBST(nums, 0, nums.length - 1);
}
public static TreeNode sortedArrayToBST(int[] num, int start, int end) {
if(start>end){
return null;
}
int mid=(start+end) >> 1;
TreeNode root=new TreeNode(num[mid]);
root.left=sortedArrayToBST(num,start,mid-1);
root.right=sortedArrayToBST(num,mid+1,end);
return root;
}
算法学习四树
最新推荐文章于 2024-11-08 17:29:00 发布