题目(一):
假设一个二叉树上面所有节点的值都为数字1~9,从根节点到任意叶子节点所经过的路径表示为12、13,则所有路径之和为12 + 13 = 25,求这道题的通用解法:
class solution {
static int i = 0;
static int total = 0;
static int COUNT = 3; //奇数,二叉树节点数量
public static void main(String[] args) {
TreeNode root = new TreeNode();
i = 0;
total = 0;
inOrderTraverse1(root); //中序遍历二叉树,并按顺序给所有节点赋值为++i
inOrderTraverse(root,0); //中序遍历二叉树,并将每条路径上的节点值之和累加到total
System.out.println("totalSum: " + total);
}
static class TreeNode{
TreeNode left;
TreeNode right;
int val;
}
public static void inOrderTraverse(TreeNode root,int pathSum) {
int sum = 0;
sum += pathSum * 10 + root.val;
if(root.left != null || root.right != null){
if(root.left != null){
inOrderTraverse(root.left,sum);
}
if(root.right != null){
inOrderTraverse(root.right,sum);
}
}else{
total += sum;
}
}
public static void inOrderTraverse1(TreeNode root) {
if (root != null) {
root.val = ++i;
System.out.println("node: " + i);
if(i > COUNT/2){
return;
}
inOrderTraverse1(root.left = new TreeNode());
inOrderTraverse1(root.right = new TreeNode());
}
}
}
题目(二):
链表内指定区间反转
将一个链表
m 位置到n 位置之间的区间反转,要求时间复杂度 ,空间复杂度 。
例如:
给出的链表为
1→2→3→4→5→NULL, ,,
返回
1→4→3→2→5→NULL.
注意:
给出的 满足以下条件:
1≤m≤n≤链表长度
示例1
输入
{1,2,3,4,5},2,4
输出
{1,4,3,2,5}
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
ListNode n1 = null;
ListNode n2 = null;
ListNode head0 = null;
if(m ==n){
return head;
}
if(m<=2){
head0 = new ListNode(0);
head0.next = head;
n1 = head0;
n2 = head0.next;
}else{
for(int i= 2;i<m;i++){
head = head.next;
}
n1 = head;
n2 = head.next;
}
for(int i = 0;i< n-m;i++){
ListNode temp = n2.next.next;
n2.next.next = n1.next;
n1.next = n2.next;
n2.next = temp;
}
if(head0 != null){
return head0.next;
}
return head;
}
}