赞
踩
1、minimum-depth-of-binary-tree
【题目】:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
【解答】:
public class Solution {
public int run(TreeNode root) {
if (root == null) {
return 0;
}
int res = 0;
if(root.left != null && root.right != null) {
res = Math.min(run(root.left), run(root.right)) +1;
} else if (root.left == null && root.right != null) {
res = run(root.right) + 1;
} else if (root.left != null && root.right == null) {
res = run(root.left) +1;
} else {
res = 1;
}
return res;
}
}
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?
【递归解法】:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
//递归版本
ArrayList<Integer> res = new ArrayList<>();
TraversalHelper(root, res);
return res;
}
public void TraversalHelper(TreeNode root, ArrayList<Integer> res) {
if (root == null) {
return;
}
TraversalHelper(root.left, res);
TraversalHelper(root.right, res);
res.add(root.val);
}
}
【非递归解法】:先序遍历: 中 左 右
在先序遍历非递归解法的基础上改成 中 右 左
然后reverse逆序编程 左 右 中, 变成了后序遍历的顺序了。
import java.util.Collections;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (stack.size() != 0) {
TreeNode node = stack.pop();
res.add(node.val);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
Collections.reverse(res);
return res;
}
}
3、binary-tree-preorder-traversal
【题目】ven 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?
【解答】
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root == null){
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (stack.size() != 0){
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right != null) stack.push(cur.right);
if (cur.left != null) stack.push(cur.left);
}
return res;
}
}
4、sum-root-to-leaf-numbers
【题目】Given a binary tree containing digits from0-9only, 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.
【解答】
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
if (root == null){
return 0;
}
int[] res = new int[1];
return generateNum(root, res, 0);
}
public int generateNum(TreeNode root, int[] res, int num){
num = num * 10 + root.val;
if (root.left != null && root.right != null){
return generateNum(root.left, res, num) + generateNum(root.right, res, num);
}
else if (root.left == null && root.right != null){
return generateNum(root.right, res, num);
}
else if (root.left != null && root.right == null){
return generateNum(root.left, res, num);
}
else {
return res[0] + num;
}
}
}
【点评】就是先序遍历,遍历到根节点再遍历左右子树时传入一个值,即高位的数值
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
Return6.
【解答】
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
int left = singleTreePathSum(root.left);
int right = singleTreePathSum(root.right);
int res = root.val;
if (left > 0) {
res += left;
}
if (right >0) {
res += right;
}
if (root.left != null) {
int subLeft = maxPathSum(root.left);
res = res > subLeft ? res : subLeft;
}
if (root.right != null) {
int subRight = maxPathSum(root.right);
res = res > subRight ? res : subRight;
}
return res;
}
//record[0]root节点左边最深路径长度,rocord[1]root节点右边
public int singleTreePathSum(TreeNode root) {
if (root == null) {
return 0;
}
int res = root.val;
int left = 0, right = 0;
if (root.left != null) {
left = singleTreePathSum(root.left);
}
if (root.right != null) {
right = singleTreePathSum(root.right);
}
int max = right > left ?right:left;
if (max >0) {
res += max;
}
return res;
}
}
6、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
【解答】
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by Administrator on 2018/3/21 0021.
*/
class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) {
val = x;
}
}
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
Queue<TreeLinkNode> queue = new LinkedList<>();
queue.add(root);
TreeLinkNode lastNode = root;
TreeLinkNode levelLastNode = root;
while (queue.size() != 0) {
TreeLinkNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
lastNode = node.left;
}
if (node.right != null) {
queue.add(node.right);
lastNode = node.right;
}
if (node == levelLastNode) {
node.next = null;
levelLastNode = lastNode;
} else {
TreeLinkNode nextNode = queue.peek();
node.next = nextNode;
}
}
}
}
【点评】有点像层序遍历,用了队列,但是每到一层结尾都要设置个levelLastNode节点提醒
7、第七题是第六题的一般情况
代码完全一样的。
8、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]
]
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<Integer> tmp = new ArrayList<>();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if(root == null) {
return res;
}
print(root, tmp, sum , res);
return res;
}
public static void print(TreeNode root, ArrayList<Integer> tmp, int num , ArrayList<ArrayList<Integer>> res) {
tmp.add(root.val);
if (root.left == null && root.right == null && num - root.val == 0) {
res.add(new ArrayList<>(tmp)); //这里很关键,要将tmp复制一份,如果直接将tmp add入res,在后面退栈是tmp.remove()时候会直接在res中删除tmp最后一个值
}
if (root.left != null) {
print(root.left, tmp, num - root.val, res);
}
if (root.right != null) {
print(root.right, tmp, num - root.val, res);
}
tmp.remove(tmp.size() -1);
}
}
【点评】要将tmp复制一份,如果直接将tmp add入res,在后面退栈是tmp.remove()时候会直接在res中删除tmp最后一个值。不然root.val = 1, sum =1 的时候输出[[]],正确输出应该是[[1]]
9、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.
public class Main {
public static void main(String[] args) {
}
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null && root.val == sum) {
return true;
}
if (hasPathSum(root.left, sum - root.val)) {
return true;
}
if (hasPathSum(root.right , sum - root.val)) {
return true;
}
return false;
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
val = x;
}
}
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.
【点评】考虑用后序遍历,先返回左子树和右子树是不是二叉平衡树,是的话返回左子树和右子树的最大高度,比较,确定根节点是不是平衡二叉树。递归调用。
【注意】 return (lnum > rnum ? lnum : rnum) + 1;此处返回的是左子树和左子树深度的较大值再加一。第一次写的时候忘记加1了。
public class Solution {
public boolean flag = true;
public boolean isBalanced(TreeNode root) {
helper(root);
if (flag) {
return true;
} else {
return false;
}
}
public int helper(TreeNode root) {
if (root == null) {
return 0;
}
int lnum = 0, rnum = 0;
if (flag) {
lnum = helper(root.left);
}
if (flag) {
rnum = helper(root.right);
}
if (Math.abs(lnum - rnum) <= 1) {
return (lnum > rnum ? lnum : rnum) + 1;
} else {
flag = false;
return 0;
}
}
}
11、binary-tree-level-order-traversal-ii
题目描述
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree{3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
ArrayList<Integer> tmp = new ArrayList<>();
TreeNode lastNode = null, levelLastNode = root;
while (queue.size() != 0) { //注意while别误写成if
TreeNode node = queue.poll();
tmp.add(node.val);
if (node.left != null) {
lastNode = node.left;
queue.add(node.left);
}
if (node.right != null) {
lastNode = node.right;
queue.add(node.right);
}
if (node == levelLastNode) {
levelLastNode = lastNode;
res.add(new ArrayList<>(tmp)); //注意此处 还是要新创建一个tmp数组,不然后面tmp清零了,res数组里的tmp也清零的
tmp.clear();
}
}
Collections.reverse(res);
return res;
}
}
【点评】注意此处 还是要新创建一个tmp数组,不然后面tmp清零了,res数组里的tmp也清零的
12、construct-binary-tree-from-inorder-and-postorder-traversal
【题目】:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
【解答】:
import java.util.HashMap;
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return inPostCons(inorder, postorder, map, 0, inorder.length-1, 0, postorder.length-1);
}
TreeNode inPostCons(int[] inorder, int[] postorder, HashMap<Integer, Integer> map, int inStart, int inEnd, int pStart, int pEnd) {
if (pStart > pEnd) {
return null;
}
TreeNode node = new TreeNode(postorder[pEnd]);
int tmp = map.get(postorder[pEnd]);
node.left = inPostCons(inorder, postorder, map, inStart, tmp-1, pStart, pStart +tmp -inStart -1);
node.right = inPostCons(inorder, postorder, map, tmp +1, inEnd, pStart + tmp -inStart, pEnd-1);
return node;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。