inorder of two BST

北慕城南 提交于 2020-02-07 08:03:49

给两个bst,把它们的值按照从小到大打印。

 1 public static void print2BSTInorder(TreeNode n1, TreeNode n2, List<Integer> result) {
 2         Stack<TreeNode> stack1 = new Stack<>();
 3         Stack<TreeNode> stack2 = new Stack<>();
 4         
 5         do {
 6             while (n1 != null) {
 7                 stack1.push(n1);
 8                 n1 = n1.left;
 9             } 
10             while (n2 != null) {
11                 stack2.push(n2);
12                 n2 = n2.left;
13             }
14             if (stack2.isEmpty() || stack1.peek().value < stack2.peek().value) {
15                 n1 = stack1.pop();
16                 result.add(n1.value);
17                 n1 = n1.right; 
18             } else {
19                 n2 = stack2.pop();
20                 result.add(n2.value);
21                 n2 = n2.right;
22             }
23         } while (!stack1.isEmpty() || n1 != null || n2 != null || !stack2.isEmpty());
24     }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!