二叉树的奇数位置和偶数位置节点和之间的差异
问题陈述
给定一棵二叉树,编写一个程序查找奇数位置和偶数位置的节点和之间的差异。假设根节点处于 0 级,奇数位置,根节点的左右子节点处于 2 级,左子节点在奇数位置,右子节点在偶数位置,依此类推。
示例
5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 Sum of nodes at odd positions = 5 + 2 + (1 + 8) + (3 + 9) = 5 + 2 + 9 + 12 = 28 Sum of nodes at even level = 0 + 6 + 4 + 7 = 17 Difference = 11.
解决方案
使用层序遍历。在遍历过程中,将第一个元素标记为奇数位置,然后在遇到新元素时切换到偶数,然后再切换到下一个,依此类推。
示例
以下是 Java 中查找所需输出的程序。
import java.util.LinkedList; 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(LinkedList<Node> queue){ if(queue.isEmpty()) return 0; int evenSum = 0; int oddSum = 0; while(true){ int nodes = queue.size(); if(nodes == 0) break; boolean isOdd = true; while(nodes > 0){ Node node = queue.peek(); if(isOdd) oddSum += node.data; else evenSum += node.data; queue.remove(); nodes--; if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); isOdd = !isOdd; } } return oddSum - evenSum; } public static void main(String args[]){ Node tree = getTree(); LinkedList<Node> queue = new LinkedList<Node>(); queue.add(tree); System.out.println(difference(queue)); } }
输出
11
广告