计算二叉树奇数级和偶数级节点之和的Java程序
使用 DFS 的图遍历是一种使用递归遍历树的明显方法。下面是一个使用 DFS 遍历二叉树的算法。
先决条件
- 使用 DFS 进行图遍历
- Java基础(数组列表)
- 递归基础
算法
- Initialize the current node as root node and the parent as -1.
- Traverse the Binary Tree as the in the general DFS fashion and keep of increasing the level of the node as we traverse farther from the root node.
- While traversing we check if the level of the current node of the binary tree is even then add in even sum else add in odd sum.
- Finally, print the Absolute difference of the of even sum and the odd sum.
例子
Java
import java.util.*;
public class GFG {
// global variable declaration
static ArrayList > arr;
static int val[];
static int sum_odd = 0, sum_even = 0;
// traverses the binary-tree/tree having parameters u,
// par, level which denotes current node, current's
// parent node, current level of the tree.
static void dfs(int u, int par, int level)
{
// according to level adding the node
if (level % 2 == 0)
sum_even += val[u];
else
sum_odd += val[u];
// exploring the child of the particular node u (2
// in case of binary tree).
for (int v : arr.get(u)) {
if (v != par) {
// recursively calling the current child
// node to become parent of the next dfs
// call.
dfs(v, u, level + 1);
}
}
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n = 5;
val = new int[] { 0, 2, 10, 5, 3, 2 };
// declaration of the ArrayList size
arr = new ArrayList<>();
// initialization of each array element as ArrayList
// class
for (int i = 0; i <= n; i++)
arr.add(new ArrayList<>());
arr.get(1).add(2);
arr.get(2).add(1);
arr.get(1).add(4);
arr.get(4).add(1);
arr.get(2).add(5);
arr.get(5).add(2);
arr.get(3).add(4);
arr.get(4).add(3);
// 1(2)
// / \
// 2(10) 4(3)
// / /
// 5(2) 3(5)
// initial call of recurssion
dfs(1, -1, 0);
System.out.println(
"Absolute difference of sum of odd and even nodes of a binary tree "
+ Math.abs(sum_odd - sum_even));
}
}
输出
Absolute difference of sum of odd and even nodes of a binary tree 4
时间复杂度: O(V + E),其中V是顶点, E是边。