• 572. Subtree of Another Tree


    package LeetCode_572
    
    import java.util.*
    
    /**
     * 572. Subtree of Another Tree
     * https://leetcode.com/problems/subtree-of-another-tree/
     *
     * Given two non-empty binary trees s and t,
     * check whether tree t has exactly the same structure and node values with a subtree of s.
     * A subtree of s is a tree consists of a node in s and all of this node's descendants.
     * The tree s could also be considered as a subtree of itself.
     * */
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }
    
    class Solution {
        /*
        * solution: pre-order traversal TreeNode and check the structure
        * Time:O(n), Space:O(n)
        * */
        fun isSubtree(s: TreeNode?, t: TreeNode?): Boolean {
            val sString = preOrder(s)
            val tString = preOrder(t)
            return sString.indexOf(tString) >= 0
        }
    
        //root->left->right
        private fun preOrder(root_: TreeNode?): String {
            if (root_ == null) {
                return ""
            }
            var root = root_
            val sb = StringBuilder()
            val stack = Stack<TreeNode>()
            while (root != null || stack.isNotEmpty()) {
                if (root != null) {
                    stack.push(root)
                    //append , to avoid like: [12],[2]
                    sb.append(",")
                    sb.append(root.`val`)
                    root = root.left
                } else {
                    root = stack.pop()
                    root = root.right
                }
                //use # to represent null of root
                if (root == null) {
                    sb.append(",#")
                }
            }
            return sb.toString()
        }
    }
  • 相关阅读:
    货车运输 noip2013day1t3
    热浪 洛谷1339 (对于最短路的复习)
    10.25 考试总结
    2017.10.27
    2017.10.26 noip2013day1
    2017.10.24
    2017.10.23 noip2014day2测试
    bzoj3173 最长上升子序列 题解--Treap+nlogn求LIS
    bzoj1588 营业额统计 题解--Treap
    codevs1068 乌龟棋 题解
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13924860.html
Copyright © 2020-2023  润新知