LeetCode(二)563. Binary Tree Tilt&404.Sum of Left Leaves&108.Convert Sorted Array to BST

本文详细解析了二叉树相关的三种算法实现:计算二叉树的倾斜值、求所有左叶子节点之和以及将有序数组转换为平衡二叉搜索树,并提供了递归与非递归的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Binary Tree Tilt

题目要求如下

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between
the sum of all left subtree node values and the sum of all right
subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.

Example: Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

The sum of node values in any subtree won’t exceed the range of 32-bit
integer. All the tilt values won’t exceed the range of 32-bit integer.

题目解法如下

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

    int result=0;
    public int findTilt(TreeNode root) {
        postOrder(root);
        return result;
    }

    private int postOrder(TreeNode root) {//使用后序遍历
        if (root == null) return 0;

        int left = postOrder(root.left);
        int right = postOrder(root.right);        
        result += Math.abs(left - right);

        return left + right + root.val;
    }


}

Sum of Left Leaves

题目要求如下

Find the sum of all left leaves in a given binary tree.

Example:

 3  
/ \  
9  20
/  \    
15   7

There are two left leaves in the binary tree, with values 9 and 15
respectively. Return 24.

题目解法如下

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

    public int sumOfLeftLeaves(TreeNode root) {

        if(root==null){
            return 0;
        }
        int res=0;
        if(root.left!=null){
         if(root.left.left == null && root.left.right == null)
         //确保其是叶子结点
         { res+=root.left.val;}
        else{
            res+=sumOfLeftLeaves(root.left);
        }
        } 
         res+=sumOfLeftLeaves(root.right);

         return res;
    }
}

非递归写法如下

public int sumOfLeftLeaves(TreeNode root) {
    if(root == null) return 0;
    int ans = 0;
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);

    while(!stack.empty()) {
        TreeNode node = stack.pop();
        if(node.left != null) {
            if (node.left.left == null && node.left.right == null)
                ans += node.left.val;
            else
                stack.push(node.left);//将左结点压入栈
        }
        if(node.right != null) {
            if (node.right.left != null || node.right.right != null)
                stack.push(node.right);//将非叶子的右结点压入栈
        }
    }
    return ans;
}

Convert Sorted Array to Binary Search Tree

题目要求如下

Given an array where elements are sorted in ascending order, convert
it to a height balanced BST.

二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉搜索树。
方法使用递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0) {
        return null;
    }
    TreeNode head = helper(nums, 0, nums.length - 1);
    return head;
    }
    public TreeNode helper(int[]nums,int low,int high){
         if (low > high) { // Done
        return null;
        }
       int mid=(low+high)/2;
       TreeNode head=new TreeNode(nums[mid]);
       head.left=helper(nums,low,mid-1);
       head.right=helper(nums,mid+1,high);
       return head;
    }
}

非递归算法如下

public class Solution {

    public TreeNode sortedArrayToBST(int[] nums) {

        int len = nums.length;
        if ( len == 0 ) { return null; }

        // 0 as a placeholder
        TreeNode head = new TreeNode(0); 

        Deque<TreeNode> nodeStack       = new LinkedList<TreeNode>() {{ push(head);  }};
        Deque<Integer>  leftIndexStack  = new LinkedList<Integer>()  {{ push(0);     }};
        Deque<Integer>  rightIndexStack = new LinkedList<Integer>()  {{ push(len-1); }};

        while ( !nodeStack.isEmpty() ) {
            TreeNode currNode = nodeStack.pop();
            int left  = leftIndexStack.pop();
            int right = rightIndexStack.pop();
            int mid   = left + (right-left)/2; // avoid overflow
            currNode.val = nums[mid];
            if ( left <= mid-1 ) {
                currNode.left = new TreeNode(0);  
                nodeStack.push(currNode.left);
                leftIndexStack.push(left);
                rightIndexStack.push(mid-1);
            }
            if ( mid+1 <= right ) {
                currNode.right = new TreeNode(0);
                nodeStack.push(currNode.right);
                leftIndexStack.push(mid+1);
                rightIndexStack.push(right);
            }
        }
        return head;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值