美文网首页
LeetCode之All Elements in Two Bin

LeetCode之All Elements in Two Bin

作者: 糕冷羊 | 来源:发表于2021-04-15 15:08 被阅读0次

    问题:



    方法:
    先分别中序遍历两棵树,二叉搜索树特性是中序遍历是有序的。然后合并两个有序的list即可得到最终结果。

    package com.eric.leetcode
    
    class AllElementsInTwoBinarySearchTrees {
        fun getAllElements(root1: TreeNode?, root2: TreeNode?): List<Int> {
            val x = mutableListOf<Int>()
            midOrder(root1, x)
            val y = mutableListOf<Int>()
            midOrder(root2, y)
            val result = mutableListOf<Int>()
            var i = 0
            var j = 0
            while (x.isNotEmpty() || y.isNotEmpty()) {
                if (x.isEmpty()) {
                    result.add(y.removeAt(0))
                } else if (y.isEmpty()) {
                    result.add(x.removeAt(0))
                } else if (x.first() < y.first()) {
                    result.add(x.removeAt(0))
                } else {
                    result.add(y.removeAt(0))
                }
            }
            return result
        }
    
        private fun midOrder(root: TreeNode?, list: MutableList<Int>) {
            if (root == null) {
                return
            }
            midOrder(root.left, list)
            list.add(root.`val`)
            midOrder(root.right, list)
        }
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之All Elements in Two Bin

          本文链接:https://www.haomeiwen.com/subject/niwdlltx.html