树的递归和非追溯遍历

编程入门 行业动态 更新时间:2024-10-28 09:19:10
本文介绍了树的递归和非追溯遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通过执行二进制搜索树上的递归和非递归预序遍历,我不会获得相同的结果

I am not getting the same result by executing the recursive and non recursive preorder traversal on a binary search Tree

递归方法

public static void preorder(TreeNode root) { if (root == null) return; else { System.out.print(root); inorder(root.getLeftPtr()); inorder(root.getRightPtr()); } }

非递归方法 / p>

non recursive method

public static void preorder2(TreeNode root){ if(root==null)return; Stack<TreeNode> stack=new Stack<TreeNode>(); while(true){ while(root!=null){ //process current Node System.out.print(root); stack.push(root); root=root.getLeftPtr(); } if(stack.isEmpty())break; root=stack.pop(); root=root.getRightPtr(); } }

结果

recursive method-> 10-> 5-> 6-> 8-> 12-> 15-> 20 non recursive method-> 10-> 6-> 5-> 8-> 15-> 12-> 20

推荐答案

我认为你的递归方法应该是这样的,

I think your recursive method should be like this,

public static void preorder(TreeNode root) { if (root == null) return; else { System.out.print(root); preorder(root.getLeftPtr()); preorder(root.getRightPtr()); } }

更多推荐

树的递归和非追溯遍历

本文发布于:2023-10-15 12:18:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1494312.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   遍历

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!