问题:

  请设计一个算法,寻找二叉树中指定结点的下一个结点(即中序遍历的后继)。给定树的根结点指针TreeNode* root和结点的值int p,请返回值为p的结点的后继结点的值。保证结点的值大于等于零小于等于100000且没有重复值,若不存在后继返回-1。注意这里没有parent指针。

思路:

  本质上还是二叉树的中序遍历。所以经过前面的学习我们有递归和非递归两种解法。

  解法一(递归解法):

 1 public class Successor2 {
 2     public int findSucc(TreeNode root, int p) {
 3         if (root == null)
 4             return -1;
 5         in(root, p);
 6         return succ;
 7     }
 8 
 9     private void in(TreeNode<Integer> node, int p) {
10         if (node == null)
11             return;
12         in(node.left, p);
13         if (preValue == p) {
14             if (succ != -1)
15                 return;
16             succ = node.val;
17             // System.out.println(succ);
18             return;
19         }
20         preValue = node.val;
21         in(node.right, p);
22     }
23 
24     private int preValue = Integer.MIN_VALUE;
25     private int succ = -1;
26 
27     public static void main(String[] args) {
28         TreeNode root = buildTree(8, 6, 10);
29         root.left.left = buildTree(3, 1, 4);
30         root.right.right = buildTree(13, 11, 15);
31         root.right.left = new TreeNode(9);
32 
33         final Successor2 tool = new Successor2();
34         System.out.println(tool.findSucc(root, 8));  // 输出9
35     }
36 
37     public static <T> TreeNode<T> buildTree(T rootValue, T lValue, T rValue) {
38         TreeNode root = new TreeNode(rootValue);
39         TreeNode left = new TreeNode(lValue);
40         TreeNode right = new TreeNode(rValue);
41         root.left = left;
42         root.right = right;
43         return root;
44     }
45 
46     public static class TreeNode<T> {
47 
48         public T val;
49         public TreeNode<T> left = null;
50         public TreeNode<T> right = null;
51 
52         public TreeNode(T val) {
53             this.val = val;
54         }
55 
56     }
57 }
View Code

相关文章:

  • 2022-01-06
  • 2021-08-28
  • 2021-10-30
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
猜你喜欢
  • 2021-07-12
  • 2021-06-24
  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2021-10-15
相关资源
相似解决方案