二叉樹最近公用祖先問題(O(n) time 且只遍曆一遍,O(1) Space (不考慮函數調用棧的空間)),二叉樹space

來源:互聯網
上載者:User

二叉樹最近公用祖先問題(O(n) time 且只遍曆一遍,O(1) Space (不考慮函數調用棧的空間)),二叉樹space

問題:

找出二叉樹中兩個節點的最近公用祖先。

首先可以先參考下這個部落格http://blog.csdn.net/cxllyg/article/details/7635992 ,寫的比較詳細,包括了節點包含父指標和不包括父指標的情況,還介紹了經典的Tarjan演算法。

Tarjan演算法很精妙,但是使用了並查集,需要額外O(n)的儲存空間。上面部落格中給的第三個方法也是需要記錄根到節點的路徑,需要O(log n)空間,當然考慮到一般情況下我們遍曆樹都是遞迴的方式,所以本身方法調用棧就是O(log n)空間佔用率。 但是這是對於平衡的二叉樹而言的,在最差情況下空間佔用率還是O(n)。

所以,這裡我給的演算法不需要記錄根到節點的路徑,而且僅僅遍曆樹一遍就可以完成。

1. 首先深度遍曆樹,找到第一個節點,假設為p,這時設定兩個節點的最近公用祖先為p

2. 繼續深度遍曆,找另外一個節點q, 假設這時找到q, 那麼二者最近祖先就是p.

3. 否則,回退到上一層,這時二者的最近公用祖先也相應改成了p的父節點,因為以p為根的子樹中沒有發現另外一個節點q

4. 依此類推,找不到則繼續回退到上一層,當找到q時,對應的二者最近公用祖先也就找到了。

5. 若是p==q,直接返回p作為最近公用祖先

6. 若二者不都存在於樹中,則返回空。


public class CommonAncestor {public static void main(String[] args) {CommonAncestor ca=new CommonAncestor();TreeNode root=new TreeNode(0);TreeNode l1=new TreeNode(-1);TreeNode r1=new TreeNode(1);root.left=l1;root.right=r1;TreeNode l1l1=new TreeNode(-2);TreeNode l1r1=new TreeNode(-3);l1.left=l1l1;l1.right=l1r1;TreeNode r=ca.commonAncestor(root, l1, r1);System.out.println(r.val);}private TreeNode ancestor=null;private TreeNode firstFound=null;private boolean found=false;public CommonAncestor(){}public TreeNode commonAncestor(TreeNode root,TreeNode p,TreeNode q){this.ancestor=null;this.found=false;findCommonAncestor(root,p,q);if(found)return ancestor;elsereturn null;}private void findCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root==null)return ;if(found)return;this.findCommonAncestor(root.left, p, q);test(root,p,q);this.findCommonAncestor(root.right, p, q);test(root,p,q);}private void test(TreeNode root, TreeNode p, TreeNode q) {if(found)return;if(this.ancestor==null){if(root==p){this.ancestor=p;firstFound=p;if(p==q)found=true;}else if(root==q){this.ancestor=q;firstFound=q;if(p==q)found=true;}}else{if(root.left==this.ancestor||root.right==this.ancestor){this.ancestor=root;}if((root==p||root==q)&&root!=firstFound){found=true;}}}}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.