5.30 Tree Traversal + Tree manipulation
生活随笔
收集整理的這篇文章主要介紹了
5.30 Tree Traversal + Tree manipulation
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- Binary Tree Preorder Traversal
題目:對一棵二叉樹進行前序遍歷,并將結果存在一個List 當中
思路:使用遞歸
細節:
對于遞歸版本:注意preorderTraversal() function 返回的是一個List, 所以不正直接用 res.add(root.val), preorderTraversal(root.left), preorderTraversal(root.right)來直接遍歷
對于非遞歸版本:使用stack數據結構來輔助遍歷,根左右的遍歷順序 對于棧操作需要反向按照根右左的順序來壓入棧
- Lowest Common Ancestor of a Binary Tree
LCA
思路: divide and conquer
什么時候返回 root? -> (root == p || root == q)
什么時候返回 left ? -> left != null && right == null
什么時候返回 right ? -> right != null && left == null
- Lowest Common Ancestor of a Binary Search Tree
要利用BST的特性來提高搜索過程的效率
轉載于:https://www.cnblogs.com/kong-xy/p/9114651.html
總結
以上是生活随笔為你收集整理的5.30 Tree Traversal + Tree manipulation的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】Java里如何实现线程间通信
- 下一篇: 消息队列的四大典型使用场景