• 【数据结构练习】二叉树相关oj题集锦三


    目录

    前言

    1.二叉树的最近公共祖先

    2.从前序与中序遍历序列构造二叉树

    3.根据二叉树创建字符串

    4.二叉树前序非递归遍历实现

    变式1:二叉树中序非递归遍历实现

    变式2:二叉树后序非递归遍历实现


    前言

    编程想要学的好,刷题少不了,我们不仅要多刷题,还要刷好题!为此我开启了一个弯道超车必做好题锦集的系列,此为二叉树面试题第三篇,每篇大约5题左右。该系列会不定期更新,敬请期待!


    1.二叉树的最近公共祖先

    二叉树的最近公共祖先icon-default.png?t=N7T8https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

    方法一

    代码:

    1. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    2. if (root == null) {
    3. return null;
    4. }
    5. if (root == p || root == q) {
    6. return root;
    7. }
    8. TreeNode leftTree=lowestCommonAncestor( root.left, p, q);
    9. TreeNode rightTree=lowestCommonAncestor( root.right, p, q);
    10. if(leftTree!=null&&rightTree!=null){
    11. return root;
    12. } else if (leftTree!=null) {
    13. return leftTree;
    14. }else {
    15. return rightTree;
    16. }
    17. }

     解析:

    因考虑的所有情况

    (1)

    若该根节点为p或者q,那么自身则为最近祖先 

    (2) 

    (3) 

     方法二

    代码:

    1. class Solution {
    2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    3. if(root==null){
    4. return null;
    5. }
    6. Stack stack1 = new Stack<>();
    7. Stack stack2 = new Stack<>();
    8. getpath( root, p, stack1);
    9. getpath( root, q, stack2);
    10. int stack1size=stack1.size();
    11. int stack2size=stack2.size();
    12. if(stack1size-stack2size>0){
    13. balance(stack1,stack2size);
    14. }else {
    15. balance(stack2,stack1size);
    16. }
    17. while (!stack1.empty()){
    18. if(stack1.peek()==stack2.peek()){
    19. return stack1.pop();
    20. }else {
    21. stack1.pop();
    22. stack2.pop();
    23. }
    24. }
    25. return null;
    26. }
    27. private void balance(Stack stack,int size){
    28. while (stack.size()!=size){
    29. stack.pop();
    30. }
    31. }
    32. public boolean getpath(TreeNode root, TreeNode node, Stack stack){
    33. if(root==null){
    34. return false;
    35. }
    36. stack.push(root);
    37. if(root==node){
    38. return true;
    39. }
    40. boolean flag1=getpath(root.left,node,stack);
    41. if(flag1==true){
    42. return true;
    43. }
    44. boolean flag2=getpath(root.right,node,stack);
    45. if(flag2==true){
    46. return true;
    47. }
    48. stack.pop();
    49. return false;
    50. }
    51. }

    解析:

    • 栈1用于存储找到p结点的路径
    • 栈2用于存储找到q结点的路径

    • 然后我们对两个栈求长度,把栈长度比较长的栈进行出栈,直到两个栈长度相等
    • 然后同时出栈进行一一比对,相同则为p、q的最近公共祖先

     


    2.从前序与中序遍历序列构造二叉树

    从前序与中序遍历序列构造二叉树icon-default.png?t=N7T8https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

     代码:

    1. class Solution {
    2. private int preindex;
    3. public TreeNode buildTree(int[] preorder, int[] inorder) {
    4. return buildTreechild(preorder, inorder,0,inorder.length-1);
    5. }
    6. private TreeNode buildTreechild(int[] preorder,int[] inorder,int begin,int end){
    7. if(begin>end){
    8. return null;
    9. }
    10. TreeNode treeNode=new TreeNode(preorder[preindex]);
    11. int rootindex=findrootindex(inorder,begin, end,preorder[preindex]);
    12. preindex++;
    13. treeNode.left=buildTreechild(preorder, inorder,begin,rootindex-1);
    14. treeNode.right=buildTreechild(preorder, inorder,rootindex+1,end);
    15. return treeNode;
    16. }
    17. private int findrootindex(int[] inorder,int begin,int end,int key){
    18. for (int i = begin; i <=end ; i++) {
    19. if(inorder[i]==key){
    20. return i;
    21. }
    22. }
    23. return -1;
    24. }
    25. }

    解析:

    对于任意一颗树而言,前序遍历的形式总是 根 左子树 右子树,而中序遍历的形式总是 左子树 根 右子树。

    只要我们在中序遍历中定位到根节点,那么我们就可以分别知道左子树和右子树中的节点数目。由于同一颗子树的前序遍历和中序遍历的长度显然是相同的,因此我们就可以对应到前序遍历的结果中,对上述形式中的所有左右括号进行定位。

    这样以来,我们就知道了左子树的前序遍历和中序遍历结果,以及右子树的前序遍历和中序遍历结果,我们就可以递归地对构造出左子树和右子树,再将这两颗子树接到根节点的左右位置。

    递归左子树的部分图展示: 

     变式:从中序与后序遍历序列构造二叉树从中序与后序遍历序列构造二叉树icon-default.png?t=N7T8https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/%E3%80%81

    代码:

    1. class Solution {
    2. private int postindex;
    3. public TreeNode buildTree(int[] inorder, int[] postorder) {
    4. postindex = postorder.length - 1;
    5. return buildTreechild(postorder, inorder, 0, inorder.length - 1);
    6. }
    7. private TreeNode buildTreechild(int[] postorder, int[] inorder, int begin, int end) {
    8. if (begin > end) {
    9. return null;
    10. }
    11. TreeNode treeNode = new TreeNode(postorder[postindex]);
    12. int rootindex = findrootindex(inorder, begin, end, postorder[postindex]);
    13. postindex--;
    14. treeNode.right =buildTreechild(postorder, inorder,rootindex+1,end );
    15. treeNode.left =buildTreechild(postorder, inorder,begin,rootindex-1 );
    16. return treeNode;
    17. }
    18. private int findrootindex(int[] inorder, int begin, int end, int key) {
    19. for (int i = begin; i <= end; i++) {
    20. if (inorder[i] == key) {
    21. return i;
    22. }
    23. }
    24. return -1;
    25. }
    26. }

     


    3.根据二叉树创建字符串

    根据二叉树创建字符串icon-default.png?t=N7T8https://leetcode.cn/problems/construct-string-from-binary-tree/

     

     

     

     分析:

    代码: 

    1. class Solution {
    2. public String tree2str(TreeNode root) {
    3. StringBuffer stringBuffer = new StringBuffer();
    4. tree2strchild( root,stringBuffer);
    5. return stringBuffer.toString();
    6. }
    7. public void tree2strchild(TreeNode root,StringBuffer stringBuffer) {
    8. if(root==null){
    9. return;
    10. }
    11. stringBuffer.append(root.val);
    12. if(root.left!=null){
    13. stringBuffer.append("(");
    14. tree2strchild( root.left, stringBuffer);
    15. stringBuffer.append(")");
    16. }else {
    17. if(root.right==null){
    18. return;
    19. }else {
    20. stringBuffer.append("()");
    21. }
    22. }
    23. if(root.right!=null){
    24. stringBuffer.append("(");
    25. tree2strchild( root.right, stringBuffer);
    26. stringBuffer.append(")");
    27. }else {
    28. return;
    29. }
    30. }
    31. }

    4.二叉树前序非递归遍历实现

    代码:

    1. public void preorderprint(TreeNode root){
    2. if(root==null){
    3. return;
    4. }
    5. Stack stack = new Stack<>();
    6. TreeNode cur=root;
    7. while(cur!=null||!stack.empty()){
    8. while(cur!=null){
    9. System.out.print(cur.val+" ");
    10. stack.push(cur);
    11. cur=cur.left;
    12. }
    13. TreeNode top=stack.pop();
    14. cur=top.right;
    15. }
    16. }

     代码解读:

    当遍历的根结点为root,其基本思想为:

    1. 当root != null时,说明当前root所指的二叉树不空,因此将其添加到栈中,然后再遍历它的左子树。
    2. 当root == null时,说明该根结点为空,那么此时栈顶结点就是当前root的父结点,将栈顶结点出栈,就能根据栈顶结点访问其右子树。
    3. 若右子树为null,继续将栈顶结点出栈,访问其右子树。
    4. 如此重复,遍历完整颗树。

    变式1:二叉树中序非递归遍历实现

    与前序遍历步骤大致相同,不同的是中序遍历需要先添加root到栈中,出栈时再打印root的val.

    代码:

    1. public void inorderprint(TreeNode root){
    2. if(root==null){
    3. return;
    4. }
    5. Stack stack = new Stack<>();
    6. TreeNode cur=root;
    7. while(cur!=null||!stack.empty()){
    8. while(cur!=null){
    9. stack.push(cur);
    10. cur=cur.left;
    11. }
    12. TreeNode top=stack.pop();
    13. System.out.print(top.val+" ");
    14. cur=top.right;
    15. }
    16. }

    变式2:二叉树后序非递归遍历实现

    思路:

    首先需要得到栈顶元素,但不出栈,用top表示,如果top右节点为null,则说明top为叶子结点,可以出栈进入到顺序表类,如果不为null,则遍历top的右节点。可能重复遍历top的右子树,最终程序崩溃所以我们这里加一个变量pero进行判断。

    代码:

    1. public void postrderprint(TreeNode root){
    2. if(root==null){
    3. return;
    4. }
    5. Stack stack = new Stack<>();
    6. TreeNode cur=root;
    7. TreeNode flag=null;
    8. while(cur!=null||!stack.empty()){
    9. while(cur!=null){
    10. stack.push(cur);
    11. cur=cur.left;
    12. }
    13. TreeNode top=stack.peek();
    14. if(top.right==null||flag==top.right){
    15. System.out.print(top.val+" ");
    16. stack.pop();
    17. flag=top;
    18. }else{
    19. cur=top.right;
    20. }
    21. }
    22. }

     


    以上为我个人的小分享,如有问题,欢迎讨论!!! 

    都看到这了,不如关注一下,给个免费的赞 

  • 相关阅读:
    Java 插入公式到PPT幻灯片
    sem_post
    开发一年不到,来面试居然敢开口要20K,面完连8K都不想给~
    JAVAEE初阶相关内容第十六弹--网络编程
    Python实验二:Python程序设计之结构与复用
    怒刷LeetCode的第21天(Java版)
    金仓数据库KingbaseES数据库参考手册(服务器配置参数14. 版本和平台兼容性)
    【调制解调】AM 调幅
    偏序:正逆序比
    Windows平台下OpenCV的编译与安装
  • 原文地址:https://blog.csdn.net/WHabc2002/article/details/133681801