Given a binary tree, find the leftmost value in the last row of the tree.
See: https://leetcode.com/problems/find-bottom-left-tree-value/description/
C++:
method one:
/** * 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) { if(!root) { return 0; } int max_depth=1,res=root->val; helper(root,1,max_depth,res); return res; } void helper(TreeNode* node,int depth,int &max_depth,int &res) { if(!node) { return; } if(depth>max_depth) { max_depth=depth; res=node->val; } helper(node->left,depth+1,max_depth,res); helper(node->right,depth+1,max_depth,res); } };
Method Two:
/** * 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) { if(!root) { return 0; } int res=root->val; queue<TreeNode*> que; que.push(root); while(!que.empty()) { int n=que.size(); for(int i=0;i<n;++i) { root=que.front(); that.pop(); if(i==0) { res=root->val; } if(root->left) { que.push(root->left); } if(root->right) { que.push(root->right); } } } return res; } };
Reference: http://www.cnblogs.com/grandyang/p/6405128.html