Find Next Node in InOrder Traverse

来源:互联网 发布:知恩中学美术班好吗 编辑:程序博客网 时间:2024/05/29 02:16

在一个二叉树的 Inorder 遍历中, 找到该节点的 下一个节点


思路: There are only 2 situations. One is this node has a right sub tree, we need to find the left most node of this right tree and return it. The other is this node is has parent and we need to find the first ancestor which is not the right son of its parent.

易错点: 要先判断 是否有右孩子, 再找他的祖先中的第一个不是右孩子的。 向上时候注意要判断他parent 不是 null.


public static TreeNode findNext(TreeNode root){if(root == null)return root;if(root.right != null){TreeNode curNode = root.right;while(curNode.left != null)curNode = curNode.left;return curNode;}TreeNode curNode = root;while(curNode.parent != null && curNode == curNode.parent.right){curNode = curNode.parent;}return curNode.parent;}public static void main(String[] args) {int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };TreeNode root = TreeNode.createMinimalBST(array);for (int i = 0; i < array.length; i++) {TreeNode node = root.find(array[i]);//TreeNode next = inorderSucc(node);TreeNode next = findNext(node);if (next != null) {System.out.println(node.data + "->" + next.data);} else {System.out.println(node.data + "->" + null);}}}


0 0
原创粉丝点击