代码随想录算法 - 二叉树3

题目1513. 找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

示例 1:

img

输入: root = [2,1,3]
输出: 1

示例 2:

img

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7

提示:

  • 二叉树的节点个数的范围是 [1,104]
  • -231 <= Node.val <= 231 - 1

思路

迭代法

用辅助queue进行层序遍历就行了,直到最后一层遍历完,取出最左边的节点。

代码

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        if(!root->left && !root->right)
        {
            return root->val;
        }
        queue<TreeNode*> nodeQueue;
        TreeNode* result;
        nodeQueue.push(root);
        while(!nodeQueue.empty())
        {
            int num = nodeQueue.size();
            if(num > 0)
            {
                result = nodeQueue.front();
            }
            for(int i = 0; i < num; i++)
            {
                TreeNode* curNode = nodeQueue.front();
                nodeQueue.pop();
                if(curNode->left)
                {
                    nodeQueue.push(curNode->left);
                }
                if(curNode->right)
                {
                    nodeQueue.push(curNode->right);
                }
            }
        }
        return result->val;
    }
};

递归法

用辅助变量maxdepth和depth来判断叶子节点是否是左下角的节点,其他的部分就先序遍历做就行了。

代码

class Solution {
public:
    int result;
    int maxDepth;
    void getResult(TreeNode* root, int depth)
    {
        //碰到叶子节点判断是否为最深的左叶子
        if(!root->left && !root->right)
        {
            if(depth > maxDepth)
            {
                maxDepth = depth;
                result = root->val;
            }
            return;
        }
        if(root->left)
        {
            getResult(root->left, depth + 1);
        }
        if(root->right)
            getResult(root->right, depth + 1);
    }
    int findBottomLeftValue(TreeNode* root) {
        maxDepth = INT_MIN;
        getResult(root, 0);
        return result;
    }
};

题目2 112. 路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false

叶子节点 是指没有子节点的节点。

示例 1:

img

输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。

示例 2:

img

输入:root = [1,2,3], targetSum = 5
输出:false
解释:树中存在两条根节点到叶子节点的路径:
(1 --> 2): 和为 3
(1 --> 3): 和为 4
不存在 sum = 5 的根节点到叶子节点的路径。

示例 3:

输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。

提示:

  • 树中节点的数目在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

思路

递归法

用先序遍历,注意节点是否为叶子节点就行了。

代码

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr)
        {
            return false;
        }
        int curVal = targetSum - root->val;
        if(curVal == 0 && !root->left && !root->right)
        {
            return true;
        }
        return hasPathSum(root->left, curVal) || hasPathSum(root->right, curVal);     
    }
};

迭代法

我使用一个辅助栈stack<pair<TreeNode*, int>>对象来保存每个节点及剩余的路径,剩下的用什么遍历都可以找出目标叶子节点。

代码

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr)
        {
            return false;
        }
        stack<pair<TreeNode*, int>> nodeStack;
        nodeStack.push(make_pair(root, targetSum));
        while(!nodeStack.empty())
        {
            auto iter = nodeStack.top();
            nodeStack.pop();
            if(!iter.first->left && !iter.first->right && iter.first->val == iter.second)
            {
                return true;
            }
            if(iter.first->left)
            {
                nodeStack.push(make_pair(iter.first->left, iter.second - iter.first->val));
            }
            if(iter.first->right)
            {
                nodeStack.push(make_pair(iter.first->right, iter.second - iter.first->val));
            }
        }
        return false;
    }
};

题目3 106. 从中序与后序遍历序列构造二叉树

给定两个整数数组 inorderpostorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树

示例 1:

img

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

迭代法

用的迭代法,思路和代码随想里的递归法类似。

代码

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.empty() || postorder.empty()) return nullptr;

        // 根节点
        TreeNode* root = new TreeNode(postorder.back());
        postorder.pop_back(); // 删除最后一个元素,因为这是根节点
        
        // 找到根节点在 inorder 中的索引
        int rootIndex = 0;
        while (inorder[rootIndex] != root->val) {
            rootIndex++;
        }

        // 栈保存:parent节点,inorder左边界,inorder右边界,postorder左边界,postorder右边界,是否为左子树
        stack<tuple<TreeNode*, int, int, int, int, bool>> nodeStack;

        // 处理右子树
        if (rootIndex + 1 <= inorder.size() - 1) {
            nodeStack.push(make_tuple(root, rootIndex + 1, inorder.size() - 1, rootIndex, postorder.size() - 1, false));
        }

        // 处理左子树
        if (0 <= rootIndex - 1) {
            nodeStack.push(make_tuple(root, 0, rootIndex - 1, 0, rootIndex - 1, true));
        }

        // 遍历栈
        while (!nodeStack.empty()) {
            auto [parent, inStart, inEnd, postStart, postEnd, isLeft] = nodeStack.top();
            nodeStack.pop();

            // 新的根节点是后序遍历 postorder[postEnd] 的值
            TreeNode* curNode = new TreeNode(postorder[postEnd]);

            if (isLeft) {
                parent->left = curNode;
            } else {
                parent->right = curNode;
            }

            // 在 inorder 中找到当前节点的索引
            int inIndex = inStart;
            while (inorder[inIndex] != curNode->val) {
                inIndex++;
            }

            // 处理右子树
            if (inIndex + 1 <= inEnd) {
                nodeStack.push(make_tuple(curNode, inIndex + 1, inEnd, postEnd - (inEnd - inIndex), postEnd - 1, false));
            }

            // 处理左子树
            if (inStart <= inIndex - 1) {
                nodeStack.push(make_tuple(curNode, inStart, inIndex - 1, postStart, postStart + (inIndex - inStart) - 1, true));
            }
        }

        return root;
    }
};

posted @ 2024-09-13 18:34  酱油黑龙  阅读(251)  评论(0)    收藏  举报