二叉樹的LCA問題 ||LeetCode總結:Tree

二叉樹的LCA問題 ||LeetCode總結:Tree

來自專欄 如何快速高效學習C++?

236.Lowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree - LeetCode?

leetcode.com圖標

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: 「The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).」

_______3______

/

___5__ ___1__

/ /

6 _2 0 8

/

7 4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL)return NULL; if(root==p||root==q)return root;//情形一:樹的根節點為要查找的兩點之一,返回根結點 TreeNode* left=lowestCommonAncestor(root->left,p,q);//向左子樹搜索 TreeNode* right=lowestCommonAncestor(root->right,p,q);//向右子樹搜索 if((NULL!=left&&NULL!=right))return root;//情形二:要查找的兩點分別在左右兩子樹,返回根結點 else if(NULL!=left)return left;//情形三:要查找的兩點在同一子樹上,返回先找到的那個結點 else if(NULL!=right)return right; return NULL; }};

推薦閱讀:

在oj系統上用Python做題顯示超時,有沒有可能是因為性能的問題?
如何評價2016年3月22日網易的在線筆試系統及試題?
相同的測試用例,本地運行72ms,LeetCode上卻TLE,可能有哪些原因?
VJ爬取別的OJ的題目會不會有侵權行為?為什麼?
可不可以在Online Judge(在線評測系統)中加入類似OSU!的PP方案的Rank計算方案?

TAG:LeetCode | OnlineJudge | 演算法 |