rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

513. 找树左下角的值 #45

Open Ni-Guvara opened 1 year ago

Ni-Guvara commented 1 year ago
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {

        queue<TreeNode *> que;
        que.push(root);

        int result = 0;
        while(!que.empty())
        {
            TreeNode * node = que.front();
            que.pop();

            if(node->right)
                que.push(node->right);
            if(node->left)
                que.push(node->left);
            result = node->val;    
        }
        return result;
    }
};
Ni-Guvara commented 1 year ago

直接从右往左

rocksc30 commented 1 year ago

那我就从左往右

/**
 * 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) {

        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        TreeNode ans = root;

        while(!list.isEmpty()){
            int size = list.size();
            boolean flag = true;
            for(int i = 0; i < size; i++){
                TreeNode cur = list.poll();
                if(i == 0) ans = cur; 
                if(cur.left != null || cur.right != null){
                    flag = false;
                }
                if(cur.left != null){
                    list.offer(cur.left);
                }
                if(cur.right != null){
                    list.offer(cur.right);
                }
            }
            if(flag){
                return ans.val;
            }
        }
        return ans.val;
    }
}
rocksc30 commented 1 year ago

递归解法

/**
 * 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 {
    private int ans;
    private int maxDepth = Integer.MIN_VALUE;

    void helper(TreeNode root, int depth){

        if(root.left == null && root.right == null){
            if(depth > maxDepth){
                maxDepth = depth;
                ans = root.val;
            }
        }
        if(root.left != null){
            depth++;
            helper(root.left, depth);
            depth--;
        }
        if(root.right != null){
            depth++;
            helper(root.right, depth);
            depth--;
        }

    }

    public int findBottomLeftValue(TreeNode root) {
        helper(root, 0);
        return ans;
    }
}