LintCode 1197 · Find Bottom Left Tree Value (树遍历好题)

1197 · Find Bottom Left Tree Value
Algorithms
Medium

Description
Given a binary tree, find the leftmost value in the last row of the tree.
You may assume the tree (i.e., the given root node) is not NULL.

Example
Example 1:

Input:{2,1,3}
Output:1

Explanation:
2
/
1 3
Example 2:

Input:{1,2,3,4,5,6,#,#,7}
Output:7

Explanation:
1
/
2 3
/ \ /
4 5 6

7

解法1:遍历

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: a root of tree
     * @return: return a integer
     */
    int findBottomLeftValue(TreeNode *root) {
        res = root->val;
        helper(root, 0);
        return res;
    }
private:
    int maxDepth = 0, res = 0;
    void helper(TreeNode *root, int depth) {
        if (!root) return;
        if (!root->left && !root->right) return;
        if (depth == maxDepth) {
            maxDepth = depth + 1;
            if (root->left) {
                res = root->left->val;
            } else {
                res = root->right->val;
            }
        }
        helper(root->left, depth + 1);
        helper(root->right, depth + 1);
    }
};

另一种写法:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: a root of tree
     * @return: return a integer
     */
    int findBottomLeftValue(TreeNode *root) {
        depth = 0;
        helper(root);
        return res;
    }
private:
    int depth = 0, maxDepth = 0, res = 0;
    void helper(TreeNode *root) {
        if (!root) return;
        depth++;
        if (depth > maxDepth) {
            res = root->val;
            depth = maxDepth;
        }
        helper(root->left);
        helper(root->right);
        depth--;
    }
};

注意:上面的遍历用前中后序遍历都可以。

解法2:BFS

class Solution {
public:
    /**
     * @param root: a root of tree
     * @return: return a integer
     */
    int findBottomLeftValue(TreeNode *root) {
        queue<TreeNode *> q;
        q.push(root);
        int res = 0;
        while (!q.empty()) {
            int qSize = q.size();
            res = q.front()->val;
            for (int i = 0; i < qSize; i++) {
                TreeNode *frontNode = q.front();
                q.pop();
                if (frontNode->left) q.push(frontNode->left);
                if (frontNode->right) q.push(frontNode->right);
            }
        }
        return res;
    }

};

你可能感兴趣的:(算法,开发语言)