• LeetCode:Sum Root to Leaf Numbers


    题目链接 

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

    An example is the root-to-leaf path 1->2->3 which represents the number 123.

    Find the total sum of all root-to-leaf numbers.

    For example,

        1
       / 
      2   3

    The root-to-leaf path 1->2 represents the number 12.
    The root-to-leaf path 1->3 represents the number 13.

    Return the sum = 12 + 13 = 25.                                                                                                                                                 本文地址

    分析:简单的树的遍历,下面代码使用队列,没有使用递归,队列节点除了存储节点地址还存储了从根节点到该节点路径表示的值。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     struct Qnode
    13     {
    14       int sum_;
    15       TreeNode* p_;
    16       Qnode(int s, TreeNode *p):sum_(s),p_(p){}
    17       Qnode(){}
    18     };
    19     int sumNumbers(TreeNode *root) {
    20         // IMPORTANT: Please reset any member data you declared, as
    21         // the same Solution instance will be reused for each test case.
    22         if(root == NULL)return 0;
    23         queue<Qnode> myqueue;
    24         myqueue.push(Qnode(root->val, root));
    25         int res = 0;
    26         while(myqueue.empty() == false)
    27         {
    28             Qnode tmp = myqueue.front();
    29             myqueue.pop();
    30             if(tmp.p_->left == NULL && tmp.p_->right == NULL)
    31                 res += tmp.sum_;
    32             else
    33             {
    34                 if(tmp.p_->left != NULL)
    35                     myqueue.push(Qnode(tmp.sum_*10 + tmp.p_->left->val, tmp.p_->left));
    36                 if(tmp.p_->right != NULL)
    37                     myqueue.push(Qnode(tmp.sum_*10 + tmp.p_->right->val, tmp.p_->right));
    38             }
    39         }
    40         return res;
    41     }
    42 };

    【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3421697.html

  • 相关阅读:
    Git Merge Request
    Hazelcast Hazelcast介绍与使用
    Git 修改name/author信息
    HDU 2553 N皇后问题(DFS)
    HDU 1070 Milk(水题)
    HDU 2616 Kill the monster(简单DFS)
    HDU 1426 Sudoku Killer(BFS)
    HDU 2216 Game III(BFS)
    URAL 1001 Reverse Root(水题)
    URAL 1902 NeoVenice(水题)
  • 原文地址:https://www.cnblogs.com/TenosDoIt/p/3421697.html
Copyright © 2020-2023  润新知