leetcode-404-Sum of Left Leaves

来源:互联网 发布:自制mac安装盘 编辑:程序博客网 时间:2024/06/04 19:23

问题

题目:[leetcode-404]

思路

这个题刚开始想用递归写,一时每反应过来。
然后想层次遍历,一时又没反应过来。
其实,基本的算法还是遍历。层次遍历即可,但是只要左叶子。
所以,我考虑加标签,主要是想模仿线索二叉树。然后写了一个结构,加了是左孩子右孩子的标签。问题搞定。

代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /* 既然你只有左叶子才要计算,所以给左叶子一个标记。出队的时候判断一下,如果是左叶子。 那么计数,否则不计数。 */struct element{    TreeNode* root_;    int flag_;    element( TreeNode* r, int flg ) : root_(r), flag_(flg) // 1 for left, 2 for right    {}};class Solution {public:    int sumOfLeftLeaves(TreeNode* root) {        if(!root) return 0;        int ans = 0;        std::queue<element> q;        q.push( element(root, -1) );        while( !q.empty() ){            element e = q.front();            q.pop();            if( !e.root_->left && !e.root_->right )            {                if( 1 == e.flag_ )                    ans += e.root_->val;            }            if( e.root_->left )            {                q.push( element( e.root_->left, 1 ) );            }            if( e.root_->right )            {                q.push( element( e.root_->right, 2 ) );            }        }// while        return ans;    }};

思路

本质既然是便利,深度和广度应该是都可以做成这件事情的。其实深度的做法一样,加入左右标志即可。根节点需要特殊处理。

代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int sumOfLeftLeaves(TreeNode* root) {        int ans = 0;        preOrder( root, 0, ans );        return ans;    }private:    void preOrder(TreeNode* root, int flag, int& ans){        if(!root)            return;        if( !root->left && !root->right && 1==flag )            ans += root->val;        preOrder( root->left, 1, ans );        preOrder( root->right, 2, ans );    }};
0 0
原创粉丝点击