[leetcode專題]--Tree(#98-#104)

98. Validate Binary Search Tree

題目描述:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

    The left subtree of a node contains only nodes with keys less than the node''s key.
    The right subtree of a node contains only nodes with keys greater than the node's key.
    Both the left and right subtrees must also be binary search trees.

 

Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

本題要求判斷一顆tree是否為二叉搜索樹脸秽。根據(jù)二叉搜索樹的定義,只要滿足任何一個節(jié)點的左節(jié)點的值小于該節(jié)點的值厢钧,右節(jié)點的值都大于該節(jié)點的值即可补鼻“送海回憶一下二叉樹的遍歷,根據(jù)二叉搜索樹的中序遍歷是有序的特點辛馆,在這里我們采用中序遍歷遍歷整棵樹,并判斷其值是否有序豁延,便可得到本題的解昙篙。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isValidBST(root *TreeNode) bool {
    if root == nil{
        return true
    }
    var stack []*TreeNode
    cur := root
    var prev *TreeNode
    
    for len(stack)>0 || cur!=nil{
        if cur!=nil{
            stack = append(stack,cur)
            cur = cur.Left
        }else{
            cur = stack[len(stack)-1]
            stack = stack[:len(stack)-1]
            if prev!=nil &&prev.Val >= cur.Val{
                return false
            }
            
            prev = cur
            cur = cur.Right
        }
    }
    return true
}

99. Recover Binary Search Tree

題目描述:

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

    A solution using O(n) space is pretty straight forward.
    Could you devise a constant space solution?

本題依然是采用中序遍歷,主要是找到兩個錯序的節(jié)點诱咏,交換兩個節(jié)點的值即可苔可。O(n)空間的解法如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func recoverTree(root *TreeNode)  {
    cur := root
    var pre,first,second *TreeNode
    var stack []*TreeNode
    
    for cur!=nil || len(stack)>0{
        if cur != nil{
            stack = append(stack,cur)
            cur = cur.Left
        }else{
            cur = stack[len(stack)-1]
            stack = stack[:len(stack)-1]
            
            if pre != nil{
                if pre.Val > cur.Val{
                    if first == nil{
                        first = pre
                    }
                    second = cur
                }
            }
            
            pre = cur
            cur = cur.Right
        }
    }
    val := first.Val
    first.Val = second.Val
    second.Val = val
}

100. Same Tree

題目描述如下:

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

本題要求判斷兩棵樹是否為相同的樹,采用遞歸判斷即可袋狞,解法如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil{
        return true
    }else if p == nil || q == nil{
        return false
    }else
    {
        return p.Val == q.Val && isSameTree(p.Left,q.Left) && isSameTree(p.Right,q.Right)
    }
}

101. Symmetric Tree

題目描述:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

本題與上題類似焚辅,也可以采取遞歸來判斷映屋。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSymmetric(root *TreeNode) bool {
    if root == nil{
        return true
    }
    
    return isSame(root.Left,root.Right)
}

func isSame(p,q *TreeNode) bool{
    if p == nil && q == nil{
        return true
    }else if p==nil || q==nil{
        return false
    }else{
        a := isSame(p.Left,q.Right)
        b := isSame(p.Right,q.Left)
        return p.Val == q.Val && a && b
    }
}

102. Binary Tree Level Order Traversal

題目描述:

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

這里給出樹的層序遍歷的非遞歸實現(xiàn),主要是要利用queue結構同蜻。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) (ret [][]int) {
    if root == nil{
        return
    }
    
    que := []*TreeNode{root}
    for len(que) > 0{
        var res []int
        size := len(que)
        for i:=0;i < size;i++{
            cur := que[0]
            res = append(res,cur.Val)
            que = que[1:]
            if cur.Left!= nil{
                que = append(que,cur.Left)
            }
            if cur.Right!=nil{
                que = append(que,cur.Right)
            }
        }
        ret = append(ret,res)
    }
    return
}

103. Binary Tree Zigzag Level Order Traversal

題目描述:

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

本題是樹的層序遍歷的一個應用棚点,要求每一層以不同的順序打印。這里只需要考慮不同層的打印順序與層數(shù)之間的關系即可湾蔓。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func zigzagLevelOrder(root *TreeNode) (ret [][]int ){
    if root == nil{
        return
    }
    
    que := []*TreeNode{root}
    isleft := true
    
    for len(que) > 0{
        size := len(que)
        path := make([]int,size)
        for i:=0;i<size;i++{
            cur := que[0]
            que = que[1:]
            
            idx := i
            if !isleft{
                idx = size-1-i
            }
            path[idx] = cur.Val
            
            if cur.Left!=nil{
                que = append(que,cur.Left)
            }
            if cur.Right!=nil{
                que = append(que,cur.Right)
            }
        }
        ret = append(ret,path)
        isleft = !isleft
    }
    return
}

104. Maximum Depth of Binary Tree

題目描述:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

本題要求二叉樹的最大高度瘫析。與大多數(shù)與樹有關的題目類似,主要采用遞歸方法來實現(xiàn)默责。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func Max(x,y int) int{
    if x > y{
        return x
    }else{
        return y
    }
}

func maxDepth(root *TreeNode) int {
    if root == nil{
        return 0
    }
    return Max(maxDepth(root.Left),maxDepth(root.Right))+1
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末贬循,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子桃序,更是在濱河造成了極大的恐慌杖虾,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件葡缰,死亡現(xiàn)場離奇詭異亏掀,居然都是意外死亡,警方通過查閱死者的電腦和手機泛释,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進店門滤愕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人怜校,你說我怎么就攤上這事间影。” “怎么了茄茁?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵魂贬,是天一觀的道長。 經(jīng)常有香客問我裙顽,道長付燥,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任愈犹,我火速辦了婚禮键科,結果婚禮上,老公的妹妹穿的比我還像新娘漩怎。我一直安慰自己勋颖,他們只是感情好,可當我...
    茶點故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布勋锤。 她就那樣靜靜地躺著饭玲,像睡著了一般。 火紅的嫁衣襯著肌膚如雪叁执。 梳的紋絲不亂的頭發(fā)上茄厘,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天矮冬,我揣著相機與錄音,去河邊找鬼蚕断。 笑死欢伏,一個胖子當著我的面吹牛,可吹牛的內容都是我干的亿乳。 我是一名探鬼主播硝拧,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼葛假!你這毒婦竟也來了障陶?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤聊训,失蹤者是張志新(化名)和其女友劉穎抱究,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體带斑,經(jīng)...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡鼓寺,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了勋磕。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片妈候。...
    茶點故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖挂滓,靈堂內的尸體忽然破棺而出苦银,到底是詐尸還是另有隱情,我是刑警寧澤赶站,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布幔虏,位于F島的核電站,受9級特大地震影響贝椿,放射性物質發(fā)生泄漏想括。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一烙博、第九天 我趴在偏房一處隱蔽的房頂上張望瑟蜈。 院中可真熱鬧,春花似錦习勤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至眷唉,卻和暖如春予颤,著一層夾襖步出監(jiān)牢的瞬間囤官,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工蛤虐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留党饮,地道東北人。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓驳庭,卻偏偏與公主長得像刑顺,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子饲常,可洞房花燭夜當晚...
    茶點故事閱讀 44,652評論 2 354

推薦閱讀更多精彩內容