1. minimum-depth-of-binary-tree
题目描述
解题思路
递归遍历二叉树的每一个节点:
(1)如果该节点为null,返回深度为0;
(2)如果节点不为空,返回左,右孩子中较小的那个孩子的深度+1;
注意:在(2)中容易出现的问题是,如果一个节点只有左孩子,没有右孩子,那么此时返回的应该是左孩子的深度,而不应该简单的认为返回两者的最小值;
1 public class Solution { 2 public int run(TreeNode root) { 3 if(root==null) 4 return 0; 5 int right = run(root.right); 6 int left = run(root.left); 7 return (left==0 || right==0)? (left+right+1) : Math.min(left,right)+1; 8 } 9 }
2. binary-tree-postorder-traversal
题目描述
Given a binary tree, return the postorder traversal of its nodes' values. 后序遍历二叉树
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
return[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
后序遍历的顺序是:左->右->根,递归的方法很好写:
1 public class Solution { 2 ArrayList<Integer> list = new ArrayList<Integer>(); 3 public ArrayList<Integer> postorderTraversal(TreeNode root) { 4 if(root==null) 5 return list; 6 if(root.left!=null) 7 postorderTraversal(root.left); 8 if(root.right!=null) 9 postorderTraversal(root.right); 10 list.add(root.val); 11 return list; 12 } 13 }
非递归方法,使用栈来迭代:
要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。
(1)如果P不存在左孩子和右孩子,则可以直接访问它;
(2)或者P存在孩子,但是其孩子都已被访问过了,则同样可以直接访问该结点
(3)若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了
注意:每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
1 public class Solution { 2 public ArrayList<Integer> postorderTraversal(TreeNode root) { 3 ArrayList<Integer> list = new ArrayList<Integer>(); 4 if(root==null) 5 return list; 6 Stack<TreeNode> S = new Stack<TreeNode>(); 7 TreeNode preNode = null; 8 S.push(root); 9 while(!S.isEmpty()){ 10 TreeNode curNode = S.peek(); 11 if((curNode.left==null && curNode.right==null)|| 12 (preNode != null && (preNode == curNode.left || preNode == curNode.right))){ 13 list.add(curNode.val); 14 S.pop(); 15 preNode = curNode; 16 } 17 else{ 18 if(curNode.right!=null) 19 S.push(curNode.right); 20 if(curNode.left!=null) 21 S.push(curNode.left); 22 } 23 } 24 return list; 25 } 26 }
3. binary-tree-preorder-traversal
题目描述
Given a binary tree, return the preorder traversal of its nodes' values. 非递归前序遍历二叉树
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
return[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
1 public class Solution { 2 public ArrayList<Integer> preorderTraversal(TreeNode root) { 3 Stack<TreeNode> S = new Stack<TreeNode>(); 4 ArrayList<Integer> list = new ArrayList<Integer>(); 5 if(root==null){ 6 return list; 7 } 8 S.push(root); 9 while(!S.isEmpty()){ 10 TreeNode tmp = S.pop(); 11 list.add(tmp.val); 12 if(tmp.right!=null) 13 S.push(tmp.right); 14 if(tmp.left!=null) 15 S.push(tmp.left); 16 } 17 return list; 18 } 19 }
4. sum-root-to-leaf-numbers
题目描述
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
从根节点到二叉树的叶子节点的每一条路径都有可以用一个数字表示,求这些数字的和;
解题思路:
用递归来做,主要就是考虑递归条件和结束条件。递归条件即是把当前的sum乘以10并且加上当前节点传入下一函数,进行递归,最终把左右子树的总和相加。结束条件的话就是如果一个节点是叶子,那么我们应该累加到结果总和中,如果节点到了空节点,则不是叶子节点,不需要加入到结果中,直接返回0即可。本质是一次先序遍历。
1 public class Solution { 2 public int sumNumbers(TreeNode root) { 3 return Count(root, 0 ); 4 } 5 static int Count(TreeNode root,int sum){ 6 if(root==null) 7 return 0; 8 if(root.left==null&&root.right==null) 9 return sum*10+root.val; 10 return Count(root.left,sum*10+root.val)+Count(root.right,sum*10+root.val); 11 } 12 }
5. binary-tree-maximum-path-sum
题目描述
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6.
找到二叉树中和最大的一条路径(任意节点为起点,不是根节点,不重复,不相交)
解题思路:
从根节点出发,递归地去找每个节点的左右子树的最大和的路径,返回当前节点的值+左右子树中和较大的那个;
注意,遍历每一条可能的路径时,都要更新最大和是否小于当前这条路径的和,是则更新;
1 public class Solution { 2 public int sum = Integer.MIN_VALUE; 3 public int maxPathSum(TreeNode root) { 4 if(root==null) 5 return 0; 6 max(root); 7 return sum; 8 } 9 public int max(TreeNode root){ 10 if(root==null) 11 return 0; 12 int left = Math.max(0, max(root.left)); 13 int right = Math.max(0, max(root.right)); 14 sum = Math.max(sum, left+right+root.val); 15 return Math.max(left, right)+root.val; 16 } 17 }
6. populating-next-right-pointers-in-each-node
题目描述
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all next pointers are set toNULL.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
解题思路
由于是完全二叉树,所以每一个节点如果有左孩子,一定有右孩子,所以左孩子的next指向右孩子,
右孩子的next指向其父节点next的左孩子(如果父节点不为空),如果父节点的next为空,则他也指向空;
所以,如果我们知道每一层最左边的节点,那么就可以获得下一层的第一个节点以及下一层所有节点的父节点;
1 public class Solution { 2 public void connect(TreeLinkNode root) { 3 if(root==null) 4 return; 5 root.next = null; 6 TreeLinkNode node = root, next = node; 7 while(node.left!=null){ 8 next = node; 9 while(next!=null){ 10 next.left.next = next.right; 11 if(next.next!=null) 12 next.right.next = next.next.left; 13 next = next.next; 14 } 15 node = node.left; 16 } 17 } 18 }
7. populating-next-right-pointers-in-each-node-ii
题目描述
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
题目描述
与上题不同,给定的二叉树不一定是完全二叉树;
采用递归的方法,对于每一层,dummy指向每一层的第一个节点,对该层的每一个节点,处理它的孩子的next指向:
如果它有左孩子,那么prev的next就为当前节点的左孩子,并标记左孩子为prev;
如果它有右孩子,那么prev的next就为当前节点的右孩子,并标记右孩子为prev;
这样,无论是否是完全二叉树,都能实现next的正确指向。
1 public class Solution { 2 public void connect(TreeLinkNode root) { 3 if(root == null) 4 return; 5 TreeLinkNode dummy = new TreeLinkNode(-1); 6 TreeLinkNode cur; 7 TreeLinkNode prev = dummy; 8 for(cur=root; cur !=null; cur = cur.next){ 9 if(cur.left !=null) 10 { 11 prev.next = cur.left; 12 prev = prev.next; 13 } 14 if(cur.right !=null){ 15 prev.next = cur.right; 16 prev = prev.next; 17 } 18 } 19 connect(dummy.next); 20 } 21 }
8. path-sum
题目描述
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
解题思路
采用递归的思想:如果当前节点是叶子节点,且该节点的val等于sum,则返回true;
否则,递归第去判断该节点的左子树或者右子树的和是否满足sum-val。
1 public class Solution { 2 public boolean hasPathSum(TreeNode root, int sum) { 3 if(root==null) 4 return false; 5 if(root.left==null && root.right==null && root.val==sum) 6 return true; 7 return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val); 8 } 9 }
9. path-sum-ii
题目描述
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
找到路径和为sum的所有路径
解题思路
判断方法和上一题一样,关键是路径的存储
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { 3 ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); 4 if(root==null) 5 return list; 6 ArrayList<Integer> ls = new ArrayList<Integer>(); 7 find(list,ls,root,sum); 8 return list; 9 } 10 static void find(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> ls, TreeNode root, int sum){ 11 if(root==null) 12 return; 13 ls.add(root.val); 14 if(root.left==null && root.right==null && root.val==sum){ 15 list.add(ls); 16 } 17 find(list,new ArrayList<Integer>(ls),root.left, sum-root.val); 18 find(list,new ArrayList<Integer>(ls),root.right, sum-root.val); 19 } 20 }
10. balanced-binary-tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
解题思路
递归地判断每颗子树是否为高度平衡二叉树(任一节点的左右子树高度差不超过1)
1 public class Solution { 2 public boolean isBalanced(TreeNode root) { 3 if(root==null) 4 return true; 5 if(Math.abs(getDepth(root.left)-getDepth(root.right))>1) 6 return false; 7 return (isBalanced(root.left) && isBalanced(root.right)); 8 } 9 public int getDepth(TreeNode root){ 10 if(root==null) 11 return 0; 12 return 1+Math.max(getDepth(root.left),getDepth(root.right)); 13 } 14 }
11. binary-tree-level-order-traversal
题目描述
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
解题思路
二叉树的层次遍历,用广度优先搜索,采用队列实现
1 import java.util.*; 2 public class Solution { 3 public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 if(root == null){ 6 return res; 7 } 8 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 9 queue.offer(root); 10 while(!queue.isEmpty()){ 11 ArrayList<Integer> arr = new ArrayList<Integer>(); 12 int size = queue.size(); 13 TreeNode p = queue.peek(); 14 for(int i=0;i<size;i++){ 15 if(queue.peek().left!=null) 16 queue.offer(queue.peek().left); 17 if(queue.peek().right!=null) 18 queue.offer(queue.peek().right); 19 arr.add(queue.poll().val); 20 } 21 res.add(arr); 22 } 23 return res; 24 } 25 }
12. binary-tree-level-order-traversal-ii
解题思路
与上题类似,只不过每层的数据按从底向上输出,仍然按照上题的方法遍历二叉树,但是每层的结果保存在一个栈中,最后按出栈顺序保存在list里;
1 import java.util.*; 2 public class Solution { 3 public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 Stack<ArrayList<Integer>> stack = new Stack<ArrayList<Integer>>(); 6 if(root==null) 7 return res; 8 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 9 queue.offer(root); 10 while(!queue.isEmpty()){ 11 ArrayList<Integer> arr = new ArrayList<Integer>(); 12 int size = queue.size(); 13 for(int i=0;i<size;i++){ 14 if(queue.peek().left!=null) 15 queue.offer(queue.peek().left); 16 if(queue.peek().right!=null) 17 queue.offer(queue.peek().right); 18 arr.add(queue.poll().val); 19 } 20 stack.push(arr); 21 } 22 while(!stack.isEmpty()){ 23 res.add(stack.pop()); 24 } 25 return res; 26 } 27 }
13. binary-tree-zigzag-level-order-traversal
解题思路
Z字形层次遍历二叉树
与上题类似,添加一个标志,如果是偶数层,反转该层的元素即可
1 import java.util.*; 2 public class Solution { 3 public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 if(root == null){ 6 return res; 7 } 8 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 9 queue.offer(root); 10 boolean reserve = true; 11 while(!queue.isEmpty()){ 12 reserve = !reserve; 13 ArrayList<Integer> arr = new ArrayList<Integer>(); 14 int size = queue.size(); 15 TreeNode p = queue.peek(); 16 for(int i=0;i<size;i++){ 17 if(queue.peek().left!=null) 18 queue.offer(queue.peek().left); 19 if(queue.peek().right!=null) 20 queue.offer(queue.peek().right); 21 arr.add(queue.poll().val); 22 } 23 if(reserve){ 24 int len = arr.size(); 25 int t = len/2; 26 for(int i=0;i<t;i++){ 27 Collections.swap(arr,i,len-1-i); 28 } 29 } 30 res.add(arr); 31 } 32 return res; 33 } 34 }
14. maximum-depth-of-binary-tree
解题思路
求二叉树的最大深度
递归求左右子树的最大深度,每个节点的最大深度为左右子树的最大深度+1(自身)
1 public class Solution { 2 public int maxDepth(TreeNode root) { 3 return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right))); 4 } 5 }
15. symmetric-tree
给定一棵二叉树,判断其是否为对称的二叉树
解题思路
递归判断左右子树是否完全相同即可
1 public class Solution { 2 public boolean isSymmetric(TreeNode root) { 3 if(root==null) 4 return true; 5 return judge(root.left,root.right); 6 } 7 private static boolean judge(TreeNode a,TreeNode b){ 8 if(b==null && a==null) 9 return true; 10 else if((a==null && b!=null) || (a!=null && b==null)) 11 return false; 12 else 13 return (a.val==b.val && judge(a.left,b.right) && judge(a.right,b.left)); 14 } 15 }
16. same-tree
判断两棵树是否完全相同
解题思路
递归判断两个数的左子树是否完全相同且右子树完全相同
1 public class Solution { 2 public boolean isSameTree(TreeNode p, TreeNode q) { 3 if(p==null && q==null) 4 return true; 5 if( (p==null && q!=null) || (p!=null && q==null)) 6 return false; 7 return (p.val==q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right)); 8 } 9 }