- leetcode104 二叉树的最大深度
- leetcode94 二叉树的中序遍历
- leetcode102 二叉树的层序遍历
- leetcode207 二叉树的层序遍历 II
- 二叉树的锯齿形层序遍历
- 二叉树的右视图
- leetcode515 在每个树行中找最大值
- leetcode 二叉树的层平均值
- leetcode116 填充每个节点的下一个右侧节点指针
- leetcode98 验证二叉搜索树
- leetcode114 二叉树展开为链表
- leetcode124 二叉树中的最大路径和
- leetcode 208 实现Trie(前缀树)
- leetcode 236 二叉树的最近公共祖先
- leetcode 437 路径总和 III
- leetcode 538 把二叉搜索树转换为累加树
- 剑指07 重建二叉树
leetcode104 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
leetcode 104//DFS 深度优先 v1.0class Solution {public int maxDepth(TreeNode root) {if(root == null) return 0;int leftDepth = maxDepth(root.left);int rightDepth = maxDepth(root.right);return Math.max(leftDepth,rightDepth)+1;}}//v2.0class Solution {public int maxDepth(TreeNode root) {return root == null?0:Math.max(maxDepth(root.left),maxDepth(root.right))+1;}}//BFS 广度优先class Solution {public int maxDepth(TreeNode root) {if(root==null) return 0;int depth = 0;Queue<TreeNode> tree = new LinkedList<TreeNode>();tree.offer(root);while(!tree.isEmpty()){int size = tree.size();while(size>0){TreeNode node = tree.poll();if(node.left!=null) tree.offer(node.left);if(node.right!=null) tree.offer(node.right);size--;}depth++;}return depth;}}
leetcode94 二叉树的中序遍历
//v1.0 递归class Solution {List<Integer> list = new ArrayList<>();public List<Integer> inorderTraversal(TreeNode root) {if(root==null) return list;inorderTraversal(root.left);list.add(root.val);inorderTraversal(root.right);return list;}}//v2.0 迭代class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();if(root==null) return list;TreeNode curr = root;while(curr!=null||!stack.isEmpty()){if(curr!=null){stack.push(curr);curr = curr.left;}else{curr = stack.pop();list.add(curr.val);curr = curr.right;}}return list;}}
leetcode102 二叉树的层序遍历
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {if(root==null) return new ArrayList<>();List<List<Integer>> res = new ArrayList<>();Queue<TreeNode> que = new LinkedList<>();que.offer(root);while(!que.isEmpty()){int size = que.size();List<Integer> list = new ArrayList<>();while(size>0){TreeNode node = que.poll();list.add(node.val);if(node.left!=null) que.offer(node.left);if(node.right!=null) que.offer(node.right);size--;}res.add(list);}return res;}}
leetcode207 二叉树的层序遍历 II
给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {List<List<Integer>> lists = new ArrayList<>();if(root==null) return lists;Queue<TreeNode> queue = new LinkedList<>();queue.add(root);while(!queue.isEmpty()){int size = queue.size();List<Integer> list = new ArrayList<>();for(int i =0;i<size;i++){TreeNode node=queue.poll();if(node.left!=null) queue.add(node.left);if(node.right!=null) queue.add(node.right);list.add(node.val);}lists.add(list);}Collections.reverse(lists);return lists;}}
二叉树的锯齿形层序遍历
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {List<List<Integer>> res = new ArrayList<>();if(root==null) return res;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);int depth=0;//树的深度while(!queue.isEmpty()){depth++;int size = queue.size();List<Integer> list = new ArrayList<>();for(int i=0;i<size;i++){TreeNode node = queue.poll();if(node.left!=null) queue.offer(node.left);if(node.right!=null) queue.offer(node.right);list.add(node.val);}if(depth%2==0){Collections.reverse(list);}res.add(list);}return res;}}
二叉树的右视图
class Solution {public List<Integer> rightSideView(TreeNode root) {List<Integer> res = new ArrayList<>();if(root==null) return res;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while(!queue.isEmpty()){int size = queue.size();for(int i=0;i<size;i++){TreeNode node = queue.poll();if(node.left!=null) queue.offer(node.left);if(node.right!=null) queue.offer(node.right);if(i==size-1) res.add(node.val);}}return res;}}
leetcode515 在每个树行中找最大值
class Solution {public List<Integer> largestValues(TreeNode root) {List<Integer> res = new ArrayList<>();if(root==null) return res;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while(!queue.isEmpty()){int size = queue.size();int maxValue=Integer.MIN_VALUE;for(int i=0;i<size;i++){TreeNode node = queue.poll();if(node.left!=null) queue.offer(node.left);if(node.right!=null) queue.offer(node.right);//maxValue = Math.max(maxValue,node.val);if(node.val>maxValue) maxValue=node.val;}res.add(maxValue);}return res;}}
leetcode 二叉树的层平均值
class Solution {public List<Double> averageOfLevels(TreeNode root) {List<Double> res = new ArrayList<>();if(root==null) return res;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while(!queue.isEmpty()){int size = queue.size();Double sum = 0.0;for(int i=0;i<size;i++){TreeNode node = queue.poll();if(node.left!=null) queue.offer(node.left);if(node.right!=null) queue.offer(node.right);sum+=node.val;}res.add(sum/size);}return res;}}
leetcode116 填充每个节点的下一个右侧节点指针
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
class Solution {public Node connect(Node root) {if(root==null) return root;if(root.left!=null){root.left.next = root.right;if(root.next!=null&&root.right!=null){root.right.next = root.next.left;}connect(root.left);connect(root.right);}return root;}}
leetcode98 验证二叉搜索树
//v1.0 利用中序遍历,判断是否为递增,但效率较低class Solution {private List<Integer> list = new ArrayList<>();public boolean isValidBST(TreeNode root) {//中序遍历为升序的二叉树为二叉搜索树list = inorderTraversal(root);for(int i=1;i<list.size();i++){if(list.get(i)>list.get(i-1)){continue;}else{return false;}}return true;}public List<Integer> inorderTraversal(TreeNode root){if(root==null){return list;}inorderTraversal(root.left);list.add(root.val);inorderTraversal(root.right);return list;}}//v2.0class Solution {public boolean isValidBST(TreeNode root) {return valid(root,Long.MIN_VALUE, Long.MAX_VALUE);}public boolean valid(TreeNode node, long min, long max){if(node==null){return true;}if(node.val<=min||node.val>=max){return false;}return valid(node.left,min,node.val)&&valid(node.right,node.val,max);}}
leetcode114 二叉树展开为链表
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/class Solution {public void flatten(TreeNode root) {if(root==null){return;}flatten(root.left); //将root的左节点转为链表flatten(root.right); //将root的右节点转为链表TreeNode tmp = root.right;root.right = root.left;root.left = null; //将root左节点置空while(root.right!=null){root = root.right;}root.right = tmp;}}
leetcode124 二叉树中的最大路径和
class Solution {int max = Integer.MIN_VALUE;public int maxPathSum(TreeNode root) {if(root==null){return 0;}dfs(root);return Math.max;}public int dfs(TreeNode root){if(root==null){return 0;}// 根节点左侧最大值int leftMax = Math.max(dfs(root.left),0);// 根节点右侧最大值int rightMax = Math.max(dfs(root.right),0);// 更新最大值max = Math.max(max, leftMax+rightMax+root.val);return Math.max(0,root.val+Math.max(leftMax,rightMax));}}
leetcode 208 实现Trie(前缀树)
class Trie {// 子节点Trie[] children;// 是否为终点boolean isEnd;/** Initialize your data structure here. */public Trie() {children = new Trie[26];isEnd = false;}/** Inserts a word into the trie. */public void insert(String word) {Trie node = this;for(int i=0;i<word.length();i++){int index = word.charAt(i)-'a';if(node.children[index]==null){node.children[index] = new Trie();}node = node.children[index];}node.isEnd = true;}/** Returns if the word is in the trie. */public boolean search(String word) {Trie node = searchPrefix(word);return node!=null&&node.isEnd;}/** Returns if there is any word in the trie that starts with the given prefix. */public boolean startsWith(String prefix) {return searchPrefix(prefix)!=null;}public Trie searchPrefix(String word){Trie node = this;for(int i=0;i<word.length();i++){int index = word.charAt(i)-'a';if(node.children[index]==null){return null;}node = node.children[index];}return node;}}/*** Your Trie object will be instantiated and called as such:* Trie obj = new Trie();* obj.insert(word);* boolean param_2 = obj.search(word);* boolean param_3 = obj.startsWith(prefix);*/
leetcode 236 二叉树的最近公共祖先
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root == null || p==root || q==root){return root;}// 在左子树中找公共祖先TreeNode left = lowestCommonAncestor(root.left,p,q);// 在右子树中找公共祖先TreeNode right = lowestCommonAncestor(root.right,p,q);if(left==null&&right==null) return null;if(left==null) return right;if(right==null) return left;return root;}}
leetcode 437 路径总和 III
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/class Solution {int res = 0;public int pathSum(TreeNode root, int targetSum) {if(root==null){return 0;}sum(root, targetSum);pathSum(root.left, targetSum);pathSum(root.right, targetSum);return res;}public void sum(TreeNode root, int targetSum){if(root==null) return;targetSum -= root.val;if(targetSum==0) res++;sum(root.left, targetSum);sum(root.right, targetSum);}}
leetcode 538 把二叉搜索树转换为累加树
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/class Solution {int num;public TreeNode convertBST(TreeNode root) {if(root==null) return null;convertBST(root.right);root.val = root.val + num;num = root.val;convertBST(root.left);return root;}}
剑指07 重建二叉树
class Solution {private int[] preorder;private Map<Integer,Integer> map = new HashMap<>();public TreeNode buildTree(int[] preorder, int[] inorder) {//存储前序遍历this.preorder = preorder;for(int i=0;i<inorder.length;i++){map.put(inorder[i],i);//存储中序遍历,方便查找根节点}return recur(0,0,inorder.length-1);}private TreeNode recur(int preRootIndex,int inLeftIndex,int inRightIndex){if(inLeftIndex>inRightIndex) return null;TreeNode root = new TreeNode(preorder[preRootIndex]);//根节点在前序遍历中找int index = map.get(root.val);//找到根节点在中序遍历中的位置root.left = recur(preRootIndex+1,inLeftIndex,index-1);root.right = recur(preRootIndex+(index-inLeftIndex)+1,index+1,inRightIndex);return root;}}
