📌  相关文章
📜  二叉树的每个级别中二叉节点值的十进制等效值之和

📅  最后修改于: 2021-04-17 16:59:51             🧑  作者: Mango

给定一个仅包含值01的节点组成的二叉树,任务是查找通过从左到右连接同一级别的节点在每个级别上形成的二进制数的十进制等效项的总和。

例子:

方法:想法是使用队列执行级别顺序遍历,并找到在每个级别形成的数字总和。请按照以下步骤解决问题:

  • 初始化一个队列,例如Q ,以执行级别顺序遍历,并初始化一个变量,例如ans ,以存储形成的数字的总和。
  • 根节点推送到队列Q。
  • 迭代直到队列变空,然后执行以下步骤:
    • 遍历范围[1,Q.size()]并连接该级别的所有节点,并将各个节点的子级推入队列Q中
    • 查找与形成的二进制数等效的十进制数,然后将此数字添加到ans
  • 完成上述步骤后,打印ans的值作为结果总和。

下面是上述方法的实现:

C++
// CPP program for the above approach
#include 
using namespace std;
 
// Structure of a Tree Node
class TreeNode {
 public:
  int val;
  TreeNode *left, *right;
 
  TreeNode(int key) {
    val = key;
    left = right = NULL;
  }
};
 
// Function to convert binary number
// to its equivalent decimal value
int convertBinaryToDecimal(vector arr) {
  int ans = 0;
  for (int i : arr) ans = (ans << 1) | i;
 
  return ans;
}
 
// Function to calculate sum of
// decimal equivalent of binary numbers
// of node values present at each level
void decimalEquilvalentAtEachLevel(TreeNode *root) {
  int ans = 0;
 
  queue que;
 
  // Push root node into queue
  que.push(root);
 
  while (true) {
    int length = que.size();
    if (length == 0) break;
    vector eachLvl;
 
    // Connect nodes at the same
    // level to form a binary number
    while (length > 0) {
      TreeNode *temp = que.front();
      que.pop();
 
      // Append the value of the
      // current node to eachLvl
      eachLvl.push_back(temp->val);
 
      // Insert the Left child to
      // queue, if its not NULL
      if (temp->left != NULL) que.push(temp->left);
 
      // Insert the Right child to
      // queue, if its not NULL
      if (temp->right != NULL) que.push(temp->right);
 
      // Decrement length by one
      length -= 1;
 
      // Stores the front
      // element of the queue
    }
 
    // Add decimal equivalent of the
    // binary number formed on the
    // current level to ans
    ans += convertBinaryToDecimal(eachLvl);
  }
 
  // Finally print ans
  cout << ans << endl;
}
 
// Driver Code
int main()
{
   
  // Given Tree
  TreeNode *root = new TreeNode(0);
  root->left = new TreeNode(1);
  root->right = new TreeNode(0);
  root->left->left = new TreeNode(0);
  root->left->right = new TreeNode(1);
  root->right->left = new TreeNode(1);
  root->right->right = new TreeNode(1);
 
  // Function Call
  decimalEquilvalentAtEachLevel(root);
 
  return 0;
}
 
// This code is contributed by sanjeev2552


Java
// Java program for the above approach
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG {
 
    // Structure of a Tree Node
    static class TreeNode {
        int val;
        TreeNode left, right;
 
        public TreeNode(int key) {
            val = key;
            left = right = null;
        }
    }
 
    // Function to convert binary number
    // to its equivalent decimal value
    static int convertBinaryToDecimal(ArrayList arr) {
        int ans = 0;
        for (int i : arr)
            ans = (ans << 1) | i;
 
        return ans;
 
    }
 
    // Function to calculate sum of
    // decimal equivalent of binary numbers
    // of node values present at each level
    static void decimalEquilvalentAtEachLevel(TreeNode root) {
 
        int ans = 0;
 
        Queue que = new LinkedList<>();
 
        // Push root node into queue
        que.add(root);
 
        while (true) {
            int length = que.size();
            if (length == 0)
                break;
            ArrayList eachLvl = new ArrayList<>();
 
            // Connect nodes at the same
            // level to form a binary number
            while (length > 0) {
 
                TreeNode temp = que.poll();
 
                // Append the value of the
                // current node to eachLvl
                eachLvl.add(temp.val);
 
                // Insert the Left child to
                // queue, if its not NULL
                if (temp.left != null)
                    que.add(temp.left);
 
                // Insert the Right child to
                // queue, if its not NULL
                if (temp.right != null)
                    que.add(temp.right);
 
                // Decrement length by one
                length -= 1;
 
                // Stores the front
                // element of the queue
            }
 
            // Add decimal equivalent of the
            // binary number formed on the
            // current level to ans
            ans += convertBinaryToDecimal(eachLvl);
        }
 
        // Finally print ans
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args) {
 
        // Given Tree
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(0);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(1);
        root.right.left = new TreeNode(1);
        root.right.right = new TreeNode(1);
 
        // Function Call
        decimalEquilvalentAtEachLevel(root);
    }
 
    // This code is contributed by sanjeev2552
}


Python3
# Python3 program for the above approach
 
# Structure of a Tree Node
class TreeNode:
    def __init__(self, val = 0,
                 left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
# Function to convert binary number
# to its equivalent decimal value
def convertBinaryToDecimal(arr):
 
    ans = 0
 
    for i in arr:
        ans = (ans << 1) | i
 
    return ans
 
# Function to calculate sum of
# decimal equivalent of binary numbers
# of node values present at each level
def decimalEquilvalentAtEachLevel(root):
 
    ans = 0
     
    # Push root node into queue
    que = [root]
 
    while True:
        length = len(que)
        if not length:
            break
        eachLvl = []
         
        # Connect nodes at the same
        # level to form a binary number
        while length:
           
            # Stores the front
            # element of the queue
            temp = que.pop(0)
 
            # Append the value of the
            # current node to eachLvl
            eachLvl.append(temp.val)
 
            # Insert the Left child to
            # queue, if its not NULL
            if temp.left:
                que.append(temp.left)
 
            # Insert the Right child to
            # queue, if its not NULL
            if temp.right:
                que.append(temp.right)
                 
            # Decrement length by one
            length -= 1
             
        # Add decimal equivalent of the
        # binary number formed on the
        # current level to ans
        ans += convertBinaryToDecimal(eachLvl)
 
    # Finally print ans
    print(ans)
 
 
# Driver Code
 
# Given Tree
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(0)
root.left.left = TreeNode(0)
root.left.right = TreeNode(1)
root.right.left = TreeNode(1)
root.right.right = TreeNode(1)
 
# Function Call
decimalEquilvalentAtEachLevel(root)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
    
   // Structure of a Tree Node
class TreeNode{
  public int val;
  public TreeNode left,right;
};
 
static TreeNode newNode(int key){
  TreeNode temp = new TreeNode();
  temp.val = key;
  temp.left = temp.right = null;
  return temp;
}
// Function to convert binary number
// to its equivalent decimal value
static int convertBinaryToDecimal(List arr)
{  
   int ans = 0;
    foreach(int i in arr)
        ans = (ans << 1) | i;
 
    return ans;
 
}
 
// Function to calculate sum of
// decimal equivalent of binary numbers
// of node values present at each level
static void decimalEquilvalentAtEachLevel(TreeNode root){
 
    int ans = 0;
     
    Queue que = new Queue();
   
    // Push root node into queue
    que.Enqueue(root);
 
    while(true){
       int length = que.Count;
        if (length == 0)
            break;
        List eachLvl = new List();
         
        // Connect nodes at the same
        // level to form a binary number
        while(length > 0){
 
          TreeNode temp = que.Peek();
          que.Dequeue();
 
            // Append the value of the
            // current node to eachLvl
            eachLvl.Add(temp.val);
 
            // Insert the Left child to
            // queue, if its not NULL
            if (temp.left != null)
                que.Enqueue(temp.left);
 
            // Insert the Right child to
            // queue, if its not NULL
            if (temp.right!=null)
                que.Enqueue(temp.right);
                 
            // Decrement length by one
            length -= 1;
           
            // Stores the front
            // element of the queue
        }
             
        // Add decimal equivalent of the
        // binary number formed on the
        // current level to ans
        ans += convertBinaryToDecimal(eachLvl);
    }
 
    // Finally print ans
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
   
    // Given Tree
TreeNode root = newNode(0);
root.left = newNode(1);
root.right = newNode(0);
root.left.left = newNode(0);
root.left.right = newNode(1);
root.right.left = newNode(1);
root.right.right = newNode(1);
 
// Function Call
decimalEquilvalentAtEachLevel(root);
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


输出:
9

时间复杂度: O(N)
辅助空间: O(1)