Java 中二叉樹奇偶層級節點之和差
問題表述
給定一棵二叉樹,編寫一個程式計算奇數層級和偶數層級節點之和的差值。假設根節點在第 1 層級,根節點的左右子節點在第 2 層級,以此類推。
示例
5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 Sum of nodes at odd level = 5 + 1 + 4 + 8 = 18 Sum of nodes at even level = 2 + 6 + 3 + 7 + 9 = 27 Difference = -9.
解法
使用遞迴遍歷。在遍歷期間,返回根節點及其左右子節點的差值。
示例
以下是 Java 版的程式,用於計算所需輸出。
class Node {
int data;
Node left, right;
Node(int data){
this.data = data;
this.left = this.right = null;
}
}
public class JavaTester {
public static Node getTree(){
Node root = new Node(5);
root.left = new Node(2);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.left.right.left = new Node(3);
root.right.right = new Node(8);
root.right.right.right = new Node(9);
root.right.right.left = new Node(7);
return root;
}
public static int difference(Node node){
if(node == null) return 0;
return node.data - difference(node.left) - difference(node.right);
}
public static void main(String args[]){
Node tree = getTree();
System.out.println(difference(tree));
}
}輸出
-9
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP