日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode-二叉树算法总结-层次遍历,路径总和等

發(fā)布時間:2024/7/5 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode-二叉树算法总结-层次遍历,路径总和等 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
版權聲明:本文為博主原創(chuàng)文章,歡迎轉載,但請注明出處,謝謝愿意分享知識的你~~ https://blog.csdn.net/qq_32690999/article/details/80484440 </div><link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css"><div id="content_views" class="markdown_views"><!-- flowchart 箭頭圖標 勿刪 --><svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg><h1 id="二叉樹常考算法整理"><a name="t0"></a>二叉樹常考算法整理</h1>

希望通過寫下來自己學習歷程的方式幫助自己加深對知識的理解,也幫助其他人更好地學習,少走彎路。也歡迎大家來給我的Github的Leetcode算法項目點star呀~~

  • 二叉樹常考算法整理
  • 前言
  • 二叉樹的類型
  • 算法分類
    • 遍歷(Traversal)問題
      • 先序、中序與后序遍歷
      • 利用兩種遍歷結果構造二叉樹
    • 遞歸問題
      • 二叉樹最大深度
      • 二叉樹最小深度
      • 平衡二叉樹判斷
      • 相同樹
      • 對稱樹
      • 路徑總和
    • 二叉搜索樹/排序樹問題
      • 驗證二叉搜索樹
      • 唯一二叉搜索樹
      • 最低的二叉樹共同祖先

前言

二叉樹即子節(jié)點數(shù)目不超過兩個的樹,基于這個基本特性,許多算法都圍繞這種樹本身或其變體而展開。

二叉樹的類型

此部分參考一句話弄懂常見二叉樹類型

根據(jù)樹的構成特性,樹存在一些比較常見的類型,我們先來分別介紹一下:

  • 滿二叉樹

除最后一層無任何子節(jié)點外,每一層上的所有結點都有兩個子結點二叉樹。

  • 完全二叉樹

一棵二叉樹至多只有最下面的一層上的結點的度數(shù)(結點擁有的子樹數(shù))可以小于2,并且最下層上的結點都集中在該層最左邊的若干位置上,則此二叉樹成為完全二叉樹。

  • 平衡二叉樹

它是一棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,并且左右兩個子樹都是一棵平衡二叉樹

  • 二叉搜索/查找/排序樹

它或者是一棵空樹,或者是具有下列性質的二叉樹:
- 若它的左子樹不空,則左子樹上所有結點的值均小于它的根結點的值;
- 若它的右子樹不空,則右子樹上所有結點的值均大于它的根結點的值;
- 它的左、右子樹也分別為二叉搜索樹

  • 紅黑樹

屬于AVL樹(平衡二叉查找樹)的一種,對樹的高度的要求不如AVL樹那么嚴格(不是嚴格控制左、右子樹高度或節(jié)點數(shù)之差小于等于1),使得其插入結點的效率相對更高。

算法分類

遍歷(Traversal)問題

先序、中序與后序遍歷

對任一二叉樹結點,若以其本身為根結點(Root Node),它的左右子節(jié)點(left/right child),那么遍歷指的就是以某種固定順序將整個二叉樹的所有結點都過一遍。

按照根節(jié)點與子節(jié)點先后遍歷關系,一共有以下三種常見的遍歷順序:

  • 先序遍歷(Preorder)

根結點-左子結點-右子結點

  • 中序遍歷(Inorder)

左子結點-根結點-右子結點

  • 后序遍歷(Postorder)

左子結點-右子結點-根結點

遍歷,根據(jù)實現(xiàn)思路,可以分為遞歸(Recursive)和非遞歸兩種方式。遞歸相對來說更為直觀易理解,但是由于遞歸需要不斷地多重地進行函數(shù)自身調(diào)用,會需要消耗更多的棧空間。而非遞歸方式就是用一般的循環(huán)(Iteration)來進行。(而其實由于二叉樹的結構特性,許多相關的題目的解題思路都會存在遞歸和非遞歸兩種方式,只要多做幾道,就會自然體味到其中的規(guī)律。)

先給出遞歸實現(xiàn)的三種遍歷:

/** 遞歸的主要思想就是:* 由于是重復調(diào)用自身,故根據(jù)遍歷順序調(diào)整根節(jié)點與左右子節(jié)點的處理語句之間的相對順序即可。*///遞歸先序遍歷public static void recurivePreorder(TreeNode root){if(root==null)return;System.out.println(root.val);if(root.left!=null)recurivePreorder(root.left);if(root.right!=null)recurivePreorder(root.right);}//遞歸中序遍歷public static void recursiveInorder(TreeNode root){if(root==null)return;if(root.left!=null)recursiveInorder(root.left);System.out.println(root.val);if(root.right!=null)recursiveInorder(root.right);}//遞歸后序遍歷public static void recursivePostorder(TreeNode root){if(root==null)return;if(root.left!=null)recursivePostorder(root.left);if(root.right!=null)recursivePostorder(root.right);System.out.println(root.val);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

非遞歸實現(xiàn)三種遍歷:

/** 非遞歸的主要思想是:* 利用棧stack存下路過的結點,依照遍歷順序打印結點,利用stack回溯。*///非遞歸先序遍歷public static void nonRecurPreorder(TreeNode root){ArrayDeque<TreeNode> stack=new ArrayDeque<TreeNode>();while(root!=null || stack.size()!=0){if (root != null) { System.out.println(root.val); //訪問結點并入棧 stack.push(root); root = root.left; //訪問左子樹 } else { root = stack.pop(); //回溯至父親結點 root = root.right; //訪問右子樹 } }}//非遞歸中序遍歷public static void nonRecurInorder(TreeNode root){ArrayDeque<TreeNode> stack=new ArrayDeque<TreeNode>();while(root!=null || stack.size()!=0){if(root!=null){stack.push(root);root=root.left; //訪問左子樹}else{root=stack.pop(); //回溯至父親結點System.out.println(root.val); //輸出父親結點root=root.right; //訪問右子樹}}}//非遞歸后序遍歷(相對來說,是二叉樹遍歷中最為復雜的一種)// 思路:如果當前結點沒有左右子樹,或者左右子樹均已被訪問過,那么就直接訪問它;否則,將其右孩子和左孩子依次入棧。注釋:peek()函數(shù)返回棧頂?shù)脑?#xff0c;但不彈出該棧頂元素public static void nonRecurPostorder(TreeNode root){ArrayDeque<TreeNode> stack=new ArrayDeque<TreeNode>();TreeNode pre=null;TreeNode cur=null;stack.push(root);while(stack.size()!=0){cur=stack.peek();if((cur.left==null && cur.right==null) || (pre!=null && (pre==cur.left || pre==cur.right))){System.out.println(cur.val); //輸出父親結點pre=cur;stack.pop();}else{if(cur.right!=null)stack.push(cur.right);if(cur.left!=null)stack.push(cur.left);}}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

利用兩種遍歷結果構造二叉樹

上面講到,二叉樹的遍歷方式一般分為先序、中序和后序三種,其中先序和中序,或者中序和后續(xù)的遍歷的結果就可以確定第三種的遍歷結果,也即確定了一棵具體的二叉樹。(此處默認二叉樹無值相同的兩個結點)

  • 利用先序與中序構造二叉樹

(此處,我們僅對這道題進行細致分析,另兩道題目是一模一樣的思路。)

先序代表了父親-左孩子-右孩子的順序,中序代表了左孩子-父親-右孩子的順序,因此,從遍歷序列的整體來看,先序序列的第一個結點代表的就是整棵樹的根結點,而我們在中序序列中定位到這個結點后,中序序列這個結點以左的結點就是根結點左子樹上的所有結點,這個結點以右的結點就是根結點右子樹上的所有結點。然后我們將先序序列按照由中序序列那里得知的劃分,找到左右子樹的劃分邊界。以此類推,我們就可以通過不斷地交替從兩個序列中獲得構造二叉樹所需要的所有信息。

原題:LC105 Construct Binary Tree from Preorder and Inorder Traversal

public TreeNode buildTree(int[] preorder, int[] inorder) {if(preorder.length==0)return null;TreeNode root=new TreeNode(preorder[0]);if(preorder.length==1)return root;int leftSubTreeNodeNums=-1;for(int i=0;i<inorder.length;i++)if(inorder[i]==root.val) {leftSubTreeNodeNums=i;break;}root.left=buildTree(Arrays.copyOfRange(preorder, 1, leftSubTreeNodeNums+1), Arrays.copyOfRange(inorder,0,leftSubTreeNodeNums));root.right=buildTree(Arrays.copyOfRange(preorder, leftSubTreeNodeNums+1, preorder.length), Arrays.copyOfRange(inorder,leftSubTreeNodeNums+1,inorder.length));return root; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 利用中序與后序構造二叉樹
public TreeNode buildTree(int[] inorder, int[] postorder) {if(inorder.length==0)return null;if(inorder.length==1)return new TreeNode(inorder[0]);TreeNode root=new TreeNode(postorder[postorder.length-1]);int leftTreeNodeSum=0;for(int i=0;i<inorder.length;i++)if(inorder[i]==root.val){leftTreeNodeSum=i;break;}root.left=buildTree(Arrays.copyOfRange(inorder, 0, leftTreeNodeSum), Arrays.copyOfRange(postorder, 0, leftTreeNodeSum));root.right=buildTree(Arrays.copyOfRange(inorder, leftTreeNodeSum+1, inorder.length), Arrays.copyOfRange(postorder, leftTreeNodeSum, postorder.length-1));return root; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

遞歸問題

遞歸解二叉樹問題時,一般以一棵三結點或更多結點的小樹作為思考解法的參照物,然后考慮一下遞歸的返回情況(一般是碰到空結點的時候)如何處理。

二叉樹最大深度

原題:LC104 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
  • 1
  • 2
  • 3
  • 4
  • 5

return its depth = 3.

  • My Answer
// 思路:典型的遞歸思路,整顆樹的最大深度等于左右子樹的最大深度+1。 public int maxDepth(TreeNode root) {if(root==null)return 0;elsereturn 1+Math.max(maxDepth(root.left),maxDepth(root.right)); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二叉樹最小深度

原題:LC111 Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest 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
  • 1
  • 2
  • 3
  • 4
  • 5

return its minimum depth = 2.

  • My Answer
// 思路:根據(jù)左右孩子的不同情況分別返回不同的相應深度,在左右孩子均存在時,返回深度較小的那一邊,以獲得最小深度。 public int minDepth(TreeNode root) {if(root==null)return 0;else if(root.left==null && root.right==null)return 1;else if(root.left!=null && root.right!=null)return 1+Math.min(minDepth(root.left), minDepth(root.right));elseif(root.left!=null)return 1+minDepth(root.left);elsereturn 1+minDepth(root.right); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

平衡二叉樹判斷

原題:LC110 Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

3/ \ 9 20/ \ 15 7
  • 1
  • 2
  • 3
  • 4
  • 5

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

1/ \ 2 2/ \ 3 3/ \ 4 4
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Return false.

  • My Answer
//思路:判斷整棵樹是否為平衡二叉樹,等價于判斷根節(jié)點的左右子樹的高度差是否小于等于1,且左右子樹是否也都為平衡二叉樹。 // 而判斷高度差的方法可以利用前面求二叉樹最大深度的方法,去分別算出左右子樹的高度作差。public static boolean isBalanced(TreeNode root) {if(root==null)return true;else {if(Math.abs(getMaxTreeDepth(root.left)-getMaxTreeDepth(root.right))<=1){return isBalanced(root.left) && isBalanced(root.right);}else {return false;}}}public static int getMaxTreeDepth(TreeNode root) {if(root==null)return 0;elsereturn 1+Math.max(getMaxTreeDepth(root.left),getMaxTreeDepth(root.right));}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

相同樹

原題:LC100 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Example 2:

Input: 1 1/ \2 2[1,2], [1,null,2]Output: false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Example 3:

Input: 1 1/ \ / \ 2 1 1 2[1,2,1], [1,1,2]Output: false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • My Answer
// 思路:逐結點判斷,若每個結點都相同,那么整棵樹就相同。 public boolean isSameTree(TreeNode p, TreeNode q) {if(p==null && q==null) {return true;}else if(p!=null && q!=null){if(p.val==q.val)return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);elsereturn false;}elsereturn false; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

對稱樹

原題:LC101 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
  • 1
  • 2
  • 3
  • 4
  • 5

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

1/ \ 2 2\ \ 3 3
  • 1
  • 2
  • 3
  • 4
  • 5

Note:

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

  • My Answer
// 思路:判斷對稱樹即判斷左右子樹鏡面對稱位置的結點是否均存在,且值相同。 public boolean isSymmetric(TreeNode root) {return isMirror(root,root); }public boolean isMirror(TreeNode t1, TreeNode t2) {if (t1 == null && t2 == null) return true;if (t1 == null || t2 == null) return false;return (t1.val == t2.val)&& isMirror(t1.right, t2.left)&& isMirror(t1.left, t2.right); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

路徑總和

原題:LC112 Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

5/ \ 4 8/ / \ 11 13 4/ \ \ 7 2 1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

  • My Answer
// 思路:注意題意是找一條“從根節(jié)點到葉子結點”的路徑和,所以到每一個結點判斷是否值對的同時,還要判斷是否沒有孩子結點,如果有,還需要繼續(xù)往下找。 public boolean hasPathSum(TreeNode root, int sum) {if(root==null)return false;if(root.val==sum && root.left==null && root.right==null)return true;int goal=sum-root.val;return hasPathSum(root.left, goal) || hasPathSum(root.right, goal); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

二叉搜索樹/排序樹問題

二叉排序樹的特點前面提到過,即對于任一樹中結點,其左子樹的結點的值均小于它,而右子樹的結點的值均大于它。根據(jù)這個特性,也存在一系列相關的算法題。

而由于依然是二叉樹,故也常見用遞歸思路解決搜索樹相關的題目。

驗證二叉搜索樹

LC98 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:

Input:

2/ \1 3 Output: true
  • 1
  • 2
  • 3
  • 4

Example 2:

5/ \ 1 4/ \ 3 6 Output: false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Explanation: The input is: [5,1,4,null,null,3,6]. The root node’s value
is 5 but its right child’s value is 4.

  • My Answer
// 思路:要保證左子樹的結點值均小于父結點值,右子樹的結點值均大于父結點值,可以分別在左右子樹中搜索最大最小值的結點,如果它們的值已經(jīng)符合和父結點的大小關系,那么就只需再繼續(xù)判斷左右子樹是否也都是二叉搜索樹即可。public boolean isValidBST(TreeNode root) {if(root==null)return true;if(root.left==null && root.right==null)return true;int leftMax=findMaxValInBST(root.left, Integer.MIN_VALUE),rightMin=findMinValInBST(root.right, Integer.MAX_VALUE);if(root.val!=Integer.MIN_VALUE) {if(leftMax>=root.val)return false;}if(root.val!=Integer.MAX_VALUE) {if(rightMin<=root.val)return false;}if(root.left!=null && root.right==null)return root.left.val<root.val && isValidBST(root.left);if(root.left==null && root.right!=null)return root.right.val>root.val && isValidBST(root.right);return root.left.val<root.val && root.right.val>root.val && isValidBST(root.left) && isValidBST(root.right);}public int findMaxValInBST(TreeNode root,int maxVal) {if(root==null)return maxVal;if(root.val>maxVal)maxVal=root.val;int leftMax=findMaxValInBST(root.left, maxVal),rightMax=findMaxValInBST(root.right, maxVal);return leftMax>rightMax?leftMax:rightMax;}public int findMinValInBST(TreeNode root,int minVal) {if(root==null)return minVal;if(root.val<minVal)minVal=root.val;int leftMin=findMinValInBST(root.left, minVal),rightMin=findMinValInBST(root.right, minVal);return leftMin<rightMin?leftMin:rightMin;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

唯一二叉搜索樹

LC96 Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's:1 3 3 2 1\ / / / \ \ 3 2 1 1 3 2/ / \ \ 2 1 2 3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • My Answer
// 思路:動態(tài)規(guī)劃 // f(n)=sum(f(n-i)*f(i-1)) i=1,2,3...,n // 對于從1到n的n個結點,構成二叉搜索樹的所有情況可以以左右子樹上結點的數(shù)目來進行劃分。 // 例如左邊0個結點+右邊n-1個結點,左邊1個結點+右邊n-2個結點......,左邊n-1個結點,右邊0個結點。 // 一種情況的左右子樹的構成情況相乘,不同情況的結果加總即得到最后的解。public int numTrees(int n) {int numTrees[]=new int[n+1];numTrees[0]=1;numTrees[1]=1;for(int i=2;i<=n;i++) {for(int j=1;j<=i;j++) {numTrees[i]+=numTrees[j-1]*numTrees[i-j];}}return numTrees[n];}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

最低的二叉樹共同祖先

LC235 Lowest Common Ancestor of a Binary Search Tree

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

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).”

Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]

_______6______/ \ ___2__ ___8__/ \ / \ 0 _4 7 9/ \ 3 5
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Example 1:

Input: root, p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.
  • 1
  • 2
  • 3

Example 2:

Input: root, p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
  • 1
  • 2
  • 3
  • My Answer
// 思路:根據(jù)結點p和q的值與父親結點值的大小關系判斷p與q是否位于同一子樹下,如果是,那么遞歸調(diào)用方法,如果不是,那么當前父親結點就是兩者的最低共同祖先。public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(p==q || p.right==q || p.left==q)return p;else if(q.left==p || q.right==p)return q;// if two nodes p and q are in same sub tree, then we need to go into lower layer recursively. if(root.val>p.val && root.val>q.val) {return lowestCommonAncestor(root.left, p, q);}else if (root.val<p.val && root.val<q.val) {return lowestCommonAncestor(root.right, p, q);// if p and q not in same sub tree, then root is the lowest common ancestor.}else {return root;}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-258a4616f7.css" rel="stylesheet"></div>

總結

以上是生活随笔為你收集整理的LeetCode-二叉树算法总结-层次遍历,路径总和等的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。