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
- Find Next Node in InOrder Traverse
- Find next node in bst
- find the N-th node In Inorder
- Leetcode BST Inorder Traverse
- Q4.6 find the ‘next’ node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- count duplicate in a sorted array
- 论证是一门学问 如何让你的观点有说服力-7 规则7 不要只举一个例子
- android开发学习(三)—— ListView,layoutInflater,常用数据适配器
- require(),include(),require_once()和include_once()区别
- PHP_EOL
- Find Next Node in InOrder Traverse
- Ubuntu下安装Mysql
- python 文件系统(1) os 和 os.path
- php-FPM 启动php-fpm: double free or corruption (out)
- 算法设计题目一 顺序表查找
- C# WPF 基础教程
- Andorid时间控件和日期控件的Demo(代码)
- iOS :自定义文字
- 2014.10.14遇到的问题及总结