leetcode-pp / 91alg-7-daily-check

6 stars 0 forks source link

【Day 16 】2022-04-16 - 513. 找树左下角的值 #18

Open azl397985856 opened 2 years ago

azl397985856 commented 2 years ago

513. 找树左下角的值

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

前置知识

暂无

题目描述

给定一个二叉树,在树的最后一行找到最左边的值。

示例 1:

输入:

    2
   / \
  1   3

输出:
1
 

示例 2:

输入:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

输出:
7
 
wychmod commented 2 years ago

思路

dfs 返回深度和值来判断

代码

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:

        def process(root):
            if not root:
                return 0, None
            left_height, left_val = process(root.left)
            right_height, right_val = process(root.right)

            if left_height >= right_height:
                val = left_val if left_val != None else root.val
                return left_height+1, val
            else:
                val = right_val if right_val != None else root.val
                return right_height+1, val

        height, val = process(root)
        return val

复杂度

时间复杂度On 空间复杂度On

JasonHe-WQ commented 2 years ago

思路: 层序遍历,找到最左边的节点的值即可 代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        q = [root]
        re = 0
        while q:
            re = q[0].val
            child = []
            for i in q:
                if i.left:
                    child.append(i.left)
                if i.right:
                    child.append(i.right)
            q = child
        return re
zenwangzy commented 2 years ago

idea

using bfs return the ans->val


class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> q;
        TreeNode* ans = NULL;
        q.push(root);
        while (!q.empty()) {
            ans = q.front();
            int size = q.size();
            while (size--) {
                TreeNode* cur = q.front();
                q.pop();
                if (cur->left )
                    q.push(cur->left);
                if (cur->right)
                    q.push(cur->right);
            }
        }
        return ans->val;
    }
};
xiayuhui231 commented 2 years ago

题目

找树左下角的值 https://leetcode-cn.com/problems/find-bottom-left-tree-value/comments/

思路

先遍历左边的节点,当左右树深度最大且相同时,就直接返回左值,抛弃右值。

代码

class Solution {
public:
    TreeNode* targtNode;
    int maxHigh = 0;
    int findBottomLeftValue(TreeNode* root) {
       dfs(root, 1);
       return targtNode->val;
    }

    void dfs (TreeNode* node, int higt){
        if(!node->left && !node->right){
            if(higt > maxHigh){
                targtNode = node;
                maxHigh = higt;
            }
            return;
        }
        if(node->left) dfs(node->left, higt+1);
        if(node->right) dfs(node->right, higt+1);
    }
};

复杂度

时间复杂度:O(n) 空间复杂度:O(1)

AConcert commented 2 years ago
function findBottomLeftValue(root: TreeNode | null): number {

    let queue: TreeNode[] = [];
    let current_level: TreeNode[] = [];

    if (root) {
        queue.push(root);
    }

    while (queue.length > 0) {

        current_level = queue;
        queue = [];

        for (let index = 0; index < current_level.length; index++) {
            const element: TreeNode = current_level[index];
            if (element.left) {
                queue.push(element.left);
            }
            if (element.right) {
                queue.push(element.right);
            }
        }

    }

    return current_level[0]!.val;
};
zhulin1110 commented 2 years ago

题目地址(513. 找树左下角的值)

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

题目描述

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

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

 

示例 1:

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

示例 2:

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

 

提示:

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

前置知识

思路

前序遍历 DFS

代码

JavaScript Code:


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function(root) {
    let maxDepth = 0;
    let res = root.val;

    dfs(root.left, 0);
    dfs(root.right, 0);

    return res;

    function dfs(cur, depth) {
        if (!cur) {
            return;
        }
        const curDepth = depth + 1;
        if (curDepth > maxDepth) {
            maxDepth = curDepth;
            res = cur.val;
        }
        dfs(cur.left, curDepth);
        dfs(cur.right, curDepth);
    }
};

复杂度分析

令 n 为节点数,h为树的高度

weihaoxie commented 2 years ago

思路

  1. 用两个变量记录当前遍历的最大层数,以及该层的第一个非空节点的值
  2. 采用DFS进行递归遍历

    代码

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution(object):
    def __init__(self):
        self.maxdepth = -1
        self.left = None
    
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.getBottomLeftValue(root,0)
        return self.left
    def getBottomLeftValue(self,root,depth):
        if root is None:
            return
        if depth > self.maxdepth:
            self.left = root.val
            self.maxdepth+=1
        self.getBottomLeftValue(root.left,depth+1)
        self.getBottomLeftValue(root.right,depth+1)

    复杂度

    • 时间复杂度为节点数O(n)
    • 空间复杂度为树的深度O(h)
youxucoding commented 2 years ago

4月16日

【day16】

leetcode.513. 找树左下角的值

难度 中等

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

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

示例 1:

img

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

思路:

使用max变量作为当前的最大深度,使用res变量记录当前『最深』且在『最左侧』的『叶子结点』的值。由前序遍历的顺序可知,遍历叶子结点的一定是从左到右的。所以整体思路就是前序遍历整棵树如果遇到叶子结点,判断当前结点是否处于最大深度,如果比最大深度还要大,更新res记录值。最后得到的res就是处于最深且最左侧的。

代码实现:

class Solution {
    int res = 0;
    int max = 0;
    public int findBottomLeftValue(TreeNode root) {
        traverse(root,0);
        return res;
    }
    void traverse(TreeNode root,int depth){
        if(root == null){
            return ;
        }
        depth++;
        if(root.left == null&&root.right == null && depth > max){
            max = depth;
            res = root.val;
        }
        traverse(root.left,depth);
        traverse(root.right,depth);
    }
}

复杂度分析:

mo660 commented 2 years ago

思路

使用BFS广度优先,把最后一行的第一个节点返回。

代码

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        TreeNode * res = nullptr;
        while (!q.empty())
        {
            res = q.front();
            int size = q.size();
            q.pop();
            while (size--)
            {
                TreeNode *cur = q.front();
                if (cur->left)
                    q.push(cur->left);
                if (cur->right)
                    q.push(cur->right);
            }
        }
        return res->val;
    }
};
revisegoal commented 2 years ago

二叉树

先判断是不是最底层,取最底层的第一个节点值即使答案,即判断用 depth > maxDepth而不是 >=

class Solution {
    int maxDepth = -1;
    int res = 0;
    public int findBottomLeftValue(TreeNode root) {
        dfs(root, 0);
        return res;
    }

    void dfs(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (depth > maxDepth) {
            maxDepth = depth;
            res = root.val;
        }
        dfs(root.left, depth + 1);
        dfs(root.right, depth + 1);
    }
}
flyzenr commented 2 years ago
m908 commented 2 years ago
class Solution {
public:
    void compute(TreeNode *node, int depth)
    {
        if(!node->left && !node->right)
        {
            if(depth > mCurDepth)
            {
                mCurDepth = depth;
                mTargetNode = node;
            }
            return;
        }
        if(node->left)
            compute(node->left, depth + 1);
        if(node->right)
            compute(node->right, depth + 1);
    }

    int findBottomLeftValue(TreeNode* root)
    {
        compute(root, 1);
        return mTargetNode->val;
    }

private:
    TreeNode *mTargetNode;
    int mCurDepth = 0;
};
KesuCaso commented 2 years ago
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        #bfs

        queue = deque()
        queue.append(root)
        while queue:
            node = queue.popleft()
            if node.right:
                queue.append(node.right)
            if node.left:
                queue.append(node.left)
        return node.val
duantao74520 commented 2 years ago

class Solution { public: int findBottomLeftValue_bfs(TreeNode root) { queue<TreeNode> q; TreeNode ans = NULL; q.push(root); while (!q.empty()) { ans = q.front(); int size = q.size(); while (size--) { TreeNode cur = q.front(); q.pop(); if (cur->left ) q.push(cur->left); if (cur->right) q.push(cur->right); } } return ans->val; } }

tensorstart commented 2 years ago

思路

bfs,注意js数组的深拷贝

代码

var findBottomLeftValue = function(root) {
    let layerArr=[];
    let lastArr=[];
    layerArr.push(root);
    while (layerArr.length){
        let curLayer=layerArr.concat();
        layerArr=[];
        for (let i = 0; i < curLayer.length; i++) {
            if (curLayer[i].left)
                layerArr.push(curLayer[i].left);
            if (curLayer[i].right)
                layerArr.push(curLayer[i].right);
        }
        lastArr=curLayer;
    }
    return lastArr[0].val;
};

复杂度分析

时间复杂度O(n) 空间复杂度O(n)

flaming-cl commented 2 years ago

513. 找树左下角的值

思路

class FindBottomLeftValue { constructor(root) { this.root = root; this.depth = 0; this.leftValue = Infinity; }

findBottomLeftValue() { this.findBottomLeftValueRecurr(this.root, 0); return this.leftValue; }

findBottomLeftValueRecurr(root, depth) { if (!root.left && !root.right) { if (depth > this.depth) { this.depth = depth; this.leftValue = root.val; } return; } if (root.left) { this.findBottomLeftValueRecurr(root.left, depth+1); } if (root.right) { this.findBottomLeftValueRecurr(root.right, depth+1); } } }

houyanlu commented 2 years ago

思路

BFS遍历整棵树,不同的是在遍历每一层的时候,==要把最左边的节点记录下来==,遍历完即是左边的节点

代码


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        std::queue<TreeNode *> q;
        TreeNode* result = nullptr;
        q.push(root);

        while (!q.empty()) {
            int size = q.size(); //获取当前这一层的结点个数
            for (int i = 0; i < size; i++) {//出队
                TreeNode* tmp = q.front();
                q.pop();

                if (i == 0) { //每一层最左边的结点值
                    result = tmp;        
                }  
                if (tmp->left) {
                    q.push(tmp->left);
                } 
                if (tmp->right) {
                    q.push(tmp->right);
                }
            }
        }

        return result->val;
    }
};

复杂度分析

Orangejuz commented 2 years ago

思路

BFS

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        queue = [root]
        ans = root.val
        while queue:
            ans = queue[0].val
            n = len(queue)
            for i in range(n):
                node = queue[0]
                del queue[0]
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return ans

复杂度

时间复杂度:O(N)

空间复杂度:O(N)

ViviXu-qiqi commented 2 years ago
var findBottomLeftValue = function(root) {
    const store = {val: -1, size: 0};
    helper(root, 0, store);
    return store.val;
};

function helper(root, level, store){
    if(!root) return null;

    if(store.size === level){
        store.val = root.val;
        store.size++;
    }

    helper(root.left, level + 1, store);
    helper(root.right, level + 1, store);

    return null;
}
webcoder-hk commented 2 years ago
        self.left, self.maxdep = 0, -1
        def dfs(root, dep):
            if root is None:
                return
            if dep > self.maxdep:
                self.left = root.val
                self.maxdep += 1
            dfs(root.left, dep+1)
            dfs(root.right, dep+1)
        dfs(root, 0)
        return self.left
dtldtt commented 2 years ago

2022-04-16

513. 找树左下角的值

思路

层序遍历,每到了新的一层记下第一个节点的值就好

代码


  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };

struct QueueNode {
  TreeNode *tree;
  int layer;
  QueueNode(): tree(nullptr),layer(0) {} 
  QueueNode(TreeNode *t, int cur):tree(t),layer(cur){}
};

class Solution {

public:
    int cur_layer;
    QueueNode *queue_node;
    int findBottomLeftValue(TreeNode* root) {
      if(!root) return 0;
      queue_node=new QueueNode();
      queue_node->layer=0;
      queue_node->tree=root;
      cur_layer=0;
      int ret=root->val;
      queue<QueueNode*> nodes;
      nodes.push(queue_node);
      while(!nodes.empty()){
        QueueNode *tmp=nodes.front();
        if(tmp->tree->left) {
          QueueNode *tmp_queue=new QueueNode(tmp->tree->left,tmp->layer+1); 
          nodes.push(tmp_queue);
        }
        if(tmp->tree->right){
          QueueNode *tmp_queue=new QueueNode(tmp->tree->right,tmp->layer+1); 
          nodes.push(tmp_queue);
        }
        if(cur_layer!=tmp->layer){
          ret=tmp->tree->val;
          cur_layer++;
        }
        nodes.pop();
        delete tmp;
      }
      return ret;
    }
};

复杂度分析

备注

复杂度有点儿高,参考别人代码

CShowww commented 2 years ago

思路

BFS

代码

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        queue = [root]
        ans = root.val
        while queue:
            ans = queue[0].val
            n = len(queue)
            for i in range(n):
                node = queue[0]
                del queue[0]
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return ans
taojin1992 commented 2 years ago

idea:

level-order traversal

Complexity:

Time: O(n), n = number of nodes
Space: O(n)

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int candidate = -1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.poll();
                if (i == 0) {
                    candidate = curNode.val;
                }

                if (curNode.left != null) {
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    queue.offer(curNode.right);
                }
            }
        }
        return candidate;
    }
}
testeducative commented 2 years ago

class Solution {
public:
    int left, maxDepth = -1;
    int findBottomLeftValue(TreeNode* root) {
        dfs(root, 0);
        return left;
    }

    void dfs(TreeNode* root, int depth){
        if(root == nullptr)
            return;
        if(depth > maxDepth){
            left = root->val;
            maxDepth = depth;
        }
        dfs(root->left, depth + 1);
        dfs(root->right, depth + 1);
    }
};
liuajingliu commented 2 years ago

解题思路

BFS

代码实现

javaScript

/**
* @param {TreeNode} root
* @return {number}
*/
var findBottomLeftValue = function(root) {
if(!root) return null;
const queue = [root]
let mostLeft = null;
while(queue.length > 0){
let curLevelSize = queue.length
mostLeft = queue[0]
for(let i = 0; i < curLevelSize; i++){
const curNode = queue.shift();
curNode.left && queue.push(curNode.left)
curNode.right&& queue.push(curNode.right)
}
}
return mostLeft.val
};

复杂度分析

  • 时间复杂度 $O(N)$ N为二叉树的节点
  • 空间复杂度 $O(N)$ N为二叉树的节点
bzlff commented 2 years ago

思路

层次遍历,用队列来存储

代码


from collections import deque
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        q = deque([root])
        while q:
            node = q.popleft()
            if node.right:
                q.append(node.right)
            if node.left:
                q.append(node.left)
        return node.val
duke-github commented 2 years ago

思路

BFS  使用先进先出队列替代递归 将每层的节点放入队列 在下一层出队 记录每一层的第一个左支树 循环结束后的记录值即为结果

复杂度

时间复杂度:O(n) 空间复杂度:O(n)

代码

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        nodeQueue.add(root);
        int firstVal = root.val;
        while (nodeQueue.size() > 0) {
            boolean flg = false;
            int size = nodeQueue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = nodeQueue.poll();
                if (node.left != null) {
                    nodeQueue.add(node.left);
                    if (!flg) {
                        firstVal = node.left.val;
                        flg = true;
                    }
                }
                if (node.right != null) {
                    nodeQueue.add(node.right);
                    if (!flg) {
                        firstVal = node.right.val;
                        flg = true;
                    }
                }
            }
        }
        return firstVal;
    }
}
XXjo commented 2 years ago

思路

BFS,最左边的节点就是该层第一个节点

代码

var findBottomLeftValue = function(root) {
    let queue = [];
    let cur;
    let res;
    queue.push(root);
    while(queue.length > 0){
        let curLength = queue.length;
        for(let i = 0; i < curLength; i++){
            cur = queue.shift();
            if(i === 0){
                res = cur.val;
            }
            if(cur.left !== null){
                queue.push(cur.left);
            }
            if(cur.right !== null){
                queue.push(cur.right);
            }
        }
    }
    return res;
};

复杂度分析

时间复杂度:(n)
空间复杂度:(q) q表示队列长度。最坏情况是满二叉树,此时q = (n - 1)/ 2,与n同阶

OldFashionedDog commented 2 years ago

class Solution: def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: li,queue=[],deque([[root,1]]) while queue: for _ in range(len(queue)): child,index=queue.popleft() if len(li) < index: li.append(child.val) index += 1 if child.left: queue.append([child.left,index]) if child.right: queue.append([child.right,index]) return li.pop()

yinhaoti commented 2 years ago
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        """
        Ideas: 
            BFS -> get last row first element
        TC: O(n)
        SC: O(n) -> no need to save ans -> improve to O(size of queue) -> worst O(N)
        """
        queue = collections.deque([root])
        res = None
        while queue:
            size = len(queue)
            res = queue[0].val
            for _ in range(size):
                node = queue.popleft()
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
        return res
ZETAVI commented 2 years ago

思路

广度优先递归(层序遍历)

语言

java

代码

public int findBottomLeftValue(TreeNode root) {
        if(root==null)return 0;
        LinkedList<TreeNode> nodeList = new LinkedList<>();
        nodeList.offer(root);
        TreeNode ans=null;
        while (!nodeList.isEmpty()){
            int size=nodeList.size();
            ans=nodeList.peekFirst();
            for (int i = 0; i < size; i++) {
                TreeNode t=nodeList.poll();
                if (t.left!=null)nodeList.offer(t.left);
                if (t.right!=null)nodeList.offer(t.right);
            }
        }
        return ans.val;
    }

复杂度分析

yaya-bb commented 2 years ago

题目地址(513. 找树左下角的值)

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

题目描述

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

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

 

示例 1:

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

示例 2:

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

 

提示:

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

前置知识

思路

先判断最大的深度,后获取节点值

代码

JavaScript Code:


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function(root) {

  let curMaxDepth = -1, curVal = 0;

  var dfs = function(root, curDepth){
    if(!root) return null;
    if(curDepth > curMaxDepth){
      curMaxDepth = curDepth;
      curVal = root.val;
    }

    dfs(root.left, curDepth+1)
    dfs(root.right, curDepth + 1)
  }

  dfs(root, 0)
  return curVal;
};

复杂度分析

令 n 为数组长度。

Davont commented 2 years ago

code

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function (root) {
  let res = 0;
  const queue = [root];
  while (queue.length !== 0) {
    let currentLen = queue.length;
    const arr = [];
    while (currentLen--) {
      let node = queue.shift();
      arr.push(node.val);
      node.left && queue.push(node.left);
      node.right && queue.push(node.right);
    }
    res = arr[0];
  }
  return res;
};
yinhaoti commented 2 years ago
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        """
        Ideas: 
            BFS -> get last row first element
        TC: O(n)
        SC: O(n) -> no need to save ans -> improve to O(size of queue) -> worst O(N)
        """
        queue = collections.deque([root])
        res = None
        while queue:
            size = len(queue)
            res = queue[0].val
            for _ in range(size):
                node = queue.popleft()
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
        return res

    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        """
        Ideas: DFS -> have depth -> update ans
        TC: O(n)
        SC: O(h) = O(n)

        """
        max_depth = -1
        ans = 0
        def dfs(root, depth):
            nonlocal max_depth, ans
            if not root: return
            if depth > max_depth:
                ans = root.val
                max_depth = depth
            dfs(root.left, depth + 1)
            dfs(root.right, depth + 1)
        dfs(root, 0)
        return ans
TonyLee017 commented 2 years ago

思路

dfs+递归

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        global max_level
        max_level = 0
        global left
        left = 0
        def dfs(root,level):
            if not root: return
            global max_level
            global left
            if level > max_level:
                left = root.val
                max_level = level
            dfs(root.left,level+1)
            dfs(root.right,level+1)
        dfs(root,1)
        return left

复杂度分析

floatingstarlight commented 2 years ago
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
    """
    Ideas: DFS -> have depth -> update ans
    TC: O(n)
    SC: O(h) = O(n)

    """
    max_depth = -1
    ans = 0
    def dfs(root, depth):
        nonlocal max_depth, ans
        if not root: return
        if depth > max_depth:
            ans = root.val
            max_depth = depth
        dfs(root.left, depth + 1)
        dfs(root.right, depth + 1)
    dfs(root, 0)
    return ans
JasonHe-WQ commented 2 years ago

思路: 层序遍历,记录q[0]的值 代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        q = [root]
        re = 0
        while q:
            re = q[0].val
            child = []
            for i in q:
                if i.left:
                    child.append(i.left)
                if i.right:
                    child.append(i.right)
            q = child
        return re
xiayuhui231 commented 2 years ago

代码 class Solution { public: TreeNode targtNode; int maxHigh = 0; int findBottomLeftValue(TreeNode root) { dfs(root, 1); return targtNode->val; }

void dfs (TreeNode* node, int higt){
    if(!node->left && !node->right){
        if(higt > maxHigh){
            targtNode = node;
            maxHigh = higt;
        }
        return;
    }
    if(node->left) dfs(node->left, higt+1);
    if(node->right) dfs(node->right, higt+1);
}

};

1973719588 commented 2 years ago

BFS

from collections import deque
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        que1 = deque()
        que1.appendleft(root)

        while que1:

            l = len(que1)
            ls = []
            for _ in range(l):
                node = que1.pop()
                ls.append(node.val)
                if node.left:
                    que1.appendleft(node.left)
                if node.right:
                    que1.appendleft(node.right)

        return ls[0]

空间复杂度:O(N) 时间复杂度:O(N)

zhiyuanpeng commented 2 years ago
from collections import deque
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        s = deque()
        s.append(root)
        while s:
            res = s[0].val
            length = len(s)
            for _ in range(length):
                cur = s.popleft()
                if cur.left:
                    s.append(cur.left)
                if cur.right:
                    s.append(cur.right)
        return res

time O(N) space # of nodes in most widest layer

huiminren commented 2 years ago

"""

题目

LC513 找树左下角的值

思路

BFS 层次遍历,找到最下面一层就是要返回的值

代码

class Solution(object):
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """

        ans = root.val
        queue = [root]

        while queue:
            ans = queue[0].val
            for _ in range(len(queue)):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return ans

复杂度

时间复杂度 O(n)
空间复杂度 O(n)

"""

MichaelXi3 commented 2 years ago

Idea

class Solution { public int findBottomLeftValue(TreeNode root) { // NULL condition if (root == null) { return 0;} // res: currDepth + currVal int[] res = new int[] {0, root.val}; res = finding(root, 0, res); return res[1]; }

private int[] finding(TreeNode root, int curDepth, int[] res) {
    // Update deepest situation
    if (res[0] < curDepth) {
        // Update deeper depth
        res[0] = curDepth;
        // Update node value
        res[1] = root.val;
    }       

    // Keep explore left and right branches
    // ❗️ 注意这里一定要先最 left branch 进行优先判定,因为要返回的是 bottom leftmost node!
    if (root.left != null) { finding(root.left, curDepth+1, res);}
    if (root.right != null) { finding(root.right, curDepth+1, res);}

    return res;
}

}


# Complexity
- Time: O(n)
- Space: O(n)