Find Bottom Left Tree Value
阿新 • • 發佈:2018-11-09
Given a binary tree, find the leftmost value in the last row of the tree.
/** * 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 findBottomLeftValue(TreeNode* root) { int maxlevel = 0,curlevel; TreeNode* ROOT; queue<int> level; queue<TreeNode*> q; q.push(root); level.push(0); ROOT = root; while(q.size()) { TreeNode* r = q.front(); curlevel = level.front(); level.pop(); q.pop(); if(r->left) { q.push(r->left); level.push(curlevel + 1); } if(r->right) { q.push(r->right); level.push(curlevel + 1); } if(curlevel > maxlevel) { maxlevel = curlevel; ROOT = r; } } return ROOT->val; } };