找树左下角的值

本文参考代码随想录

给定一棵树,找树最下排最左边的值

递归法

遇到叶子结点时,统计最大深度,且递归过程中依然需要回溯

class Solution {
public:
    int maxDepth = INT_MIN;
    int result;
    void traversal(TreeNode* root, int depth) {
        //是叶子结点
        if(root->left == nullptr && root->right == nullptr) {
            if(depth > maxDepth) {
                maxDepth = depth;
                result = root->val;
            }
            return;
        }
        if(root->left) {
            depth++;
            traversal(root->left, depth);
            depth--;
        }
        if(root->right){
            depth++;
            traversal(root->right, depth);
            depth--;
        }
        return;
    }
    int findBottomLeftValue(TreeNode* root) {
        traversal(root, 0);
        return result;
    }
};

迭代法

使用层序遍历记录最后一行第一个节点

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> que;
        if(root != nullptr) que.push(root);
        int result = 0;
        while(!que.empty()){
            int size = que.size();
            for(int i = 0;i < size; i++){
                TreeNode* node = que.front();
                que.pop();
                if(i == 0) result = node->val;//记录最左边元素
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
        }
        return result;
    }
};

你可能感兴趣的:(刷题必背,算法,java,数据结构)