513. Find Bottom Left Tree Value

来源:互联网 发布:cmd查找他机mac 编辑:程序博客网 时间:2024/06/05 06:57

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 depth(TreeNode *root) {        if(root == NULL){            return 0;        }        int l = 1 + depth(root->left);        int r = 1 + depth(root->right);        return l>r?l:r;    }    int findBottomLeftValue(TreeNode* root) {        queue<TreeNode *> qu;        int treeDepth = depth(root);        TreeNode * node = NULL;        if(root == NULL){            return -1;        }        qu.push(root);        while(!qu.empty()){                               treeDepth--;            if(treeDepth == 0){                node = qu.front();                return node->val;            }            int n = qu.size();            for(int i = 0;i < n;++i){                TreeNode * node = qu.front();                qu.pop();                if(node->left){                    qu.push(node->left);                }                if(node->right){                    qu.push(node->right);                }            }        }        return 0;    }};
原创粉丝点击