LeetCode | 110. Balanced Binary Tree, 257. Binary Tree Paths, 404. Sum of Left Leaves

110. Balanced Binary Tree

Link: https://leetcode.com/problems/balanced-binary-tree/

Description

Given a binary tree, determine if it is height-balanced.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Approach

  • Initialize a recursive function height with parameter root.
  • If the root is null, return 0;
  • Compute the height of left tree and right tree. If any of the subtrees’ height equals to -1, return -1.
  • If the absolute difference between left tree and right tree > 1, it means it is unblanced, return -1.
  • If the binary tree is balanced (i.e., the absolute difference in heights of its left and right subtrees is not greater than 1), the function returns the height of the current node.

Solution

/**
 * 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 boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }

    private int height(TreeNode root) {
        if (root == null)
            return 0;
        int leftHeight = height(root.left);
        if (leftHeight == -1)
            return -1;
        int rightHeight = height(root.right);
        if(rightHeight == -1)
            return -1;

        if (Math.abs(leftHeight - rightHeight) > 1)
            return -1;
        return 1 + Math.max(leftHeight, rightHeight);
    }
}

257. Binary Tree Paths

Link: https://leetcode.com/problems/binary-tree-paths/

Description

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Approach

Backtracking & Recursion

  • Initialize a recursive function with parameter root(the processing node), result (the list containing all paths), path(the list to track the value of the processed node).
  • Add the current node to the path.
  • If the root is a leaf, add the path to the result.
  • If not, for each non-leaf node, its value is added to the path list before recursively calling the recursive function for the left and right subtrees. The value is removed from the path list after processing the subtree to backtrack and explore other paths.

Iteration using stack

  • Initialize an object stack, which is used to track the node and the current path.
  • Push the root and the path (Value of the root).
  • While the stack is not empty:
    • Pop the path and the node.
    • If the node is a leaf, add the path to the result list.
    • Else, if the right child is not null, push the right child and the updated path (Add the value of the right child) to the stack. And apply the same procedure for the left child.

Solution

/**
 * 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;
 *     }
 * }
 */

//Recursion + backtracking
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        getPath(root, result, path);
        return result;
    }

    private void getPath(TreeNode root, List<String> result, List<Integer> path) {
        if (root.left == null && root.right == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < path.size(); i++) {
                sb.append(path.get(i)).append("->");
            }
            sb.append(root.val);
            result.add(sb.toString());
            path.add(root.val);
            return;
        }
        path.add(root.val);
        if (root.left != null) {
            getPath(root.left, result, path);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            getPath(root.right, result, path);
            path.remove(path.size() - 1);
        }
        return;
    }
}

//Iteration
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        Stack<Object> stack = new Stack<>();
        List<String> result = new ArrayList<>();
        stack.push(root);
        stack.push(root.val + "");
        while (!stack.isEmpty()) {
            String path = (String)stack.pop();
            TreeNode node = (TreeNode)stack.pop();

            if (node.left == null && node.right == null) {
                result.add(path);
            }
            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }
            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
        }
        return result;
    }
}

404. Sum of Left Leaves

Link: https://leetcode.com/problems/sum-of-left-leaves/

Description

Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Approach

Recursion

  • Initialize a recursive function with parameter node, which denotes the processing node.
  • If the node is null, return 0;
  • If the node contains not-null left subtree and the left child is a leaf, the left subtree is a left leaf, save it in leftLeafVal.
  • The function then recursively calls for both the left and right subtrees and adds the sum of the left subtree, the sum of the right subtree, and the leftLeafVal (if any) to get the final sum of all left leaves in the binary tree.

Iteration

  • Initialize a TreeNode stack, a sum to compute the sum of the left leaves.
  • Push the root to the stack.
  • While stack is not empty:
    • Pop the top node of the stack.
    • If the node contains not-null left subtree and the left child is a leaf, add the value of the left subtree to sum.
    • Push the right subtree and left subtree (If not null) to the stack.

Solution

/**
 * 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;
 *     }
 * }
 */
//Recursion
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return sum(root);
    }

    private int sum(TreeNode root) {
        if (root == null)
            return 0;
        int leftLeafVal = 0;
        if (root.left != null && root.left.left == null && root.left.right == null)
            leftLeafVal = root.left.val;
        return sum(root.left) + sum(root.right) + leftLeafVal;
    }
}

//Iteration
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        int sum = 0;
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null && node.left.left == null && node.left.right == null)
                sum += node.left.val;
            if (node.right != null)
                stack.push(node.right);
            if (node.left != null)
                stack.push(node.left);
        }

        return sum;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值