7、找出二叉树中序遍历的下一个节点——剑指offer
2018-05-18 18:01
375 查看
版权声明: https://blog.csdn.net/ustcer_93lk/article/details/80367803
找出中序遍历后的下一个节点
问题描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点(不存在重复数据)。树中的结点不仅包含左右子结点,同时包含指向父结点的指针
本方法思想:本题目主要考察的是逻辑分析能力,不存在什么算法知识,具体的分析在代码中有注释,分几种情况导论即可,直接去看代码getNext方法吧。
持续更新...
代码附下
Java实现:
package 找出中序遍历后的下一个节点; /** * 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回 * @author user *树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 */
class TreeNode { String val; TreeNode left = null; TreeNode right = null; TreeNode father = null; public TreeNode(String val) { this.val = val; } } public class NextNode { public static void main(String[] args) { TreeNode t1 = new TreeNode("A"); TreeNode t2 = new TreeNode("B"); TreeNode t3 = new TreeNode("C"); TreeNode t4 = new TreeNode("D"); TreeNode t5 = new TreeNode("E"); TreeNode t6 = new TreeNode("F"); TreeNode t7 = new TreeNode("G"); TreeNode t8 = new TreeNode("H"); TreeNode t9 = new TreeNode("I"); t1.left = t2; t1.right = t3; t2.father = t1; t2.left = t4; t2.right = t5; t3.father = t1; t3.left = t6; t3.right = t7; t4.father = t2; t5.father = t2; t5.left = t8; t5.right = t9; t6.father = t3; t7.father = t3; t8.father = t5; t9.father = t5; System.out.println("中序遍历结果:"); printTree(t1); System.out.println(); TreeNode serch = t1; String string = getNext(serch); System.out.println(serch.val + "后面的是:" + string); } public static void printTree(TreeNode root) { if (root != null) { printTree(root.left); System.out.print(root.val + " "); printTree(root.right); } } private static String getNext(TreeNode tree) { // TODO Auto-generated method stub // 如果有右孩子,则下一个节点是右孩子中最左子节点 TreeNode temp; if (tree.right != null) { temp = tree.right; while (temp.left != null) { temp = temp.left; } return temp.val; } // 节点是其父节点的左子节点,则下一个节点就是父节点(节点没有右孩子) if (tree.father != null && tree.father.left == tree) { return tree.father.val; } // 如果节点是父节点的右子节点(节点没有右孩子),下一个节点:父节点是其父节点的左孩子 if (tree.father != null && tree.father.right == tree) { temp = tree.father; while (temp != null) { if (temp.father.left == temp) { return temp.father.val; } temp = temp.father; } // 最后没找到的话 就说明这是最后一个,不存在他的下一个了 } return null; } }
持续更新...欢迎赞赏!
https://blog.csdn.net/ustcer_93lk/article/details/80367803
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。
阅读更多相关文章推荐
- 剑指offer:找到二叉树中序遍历的下一个节点
- 剑指offer-二叉树的下一个节点
- (C++)剑指offer-57:二叉树的下一个节点(树)
- 【剑指offer】面试题8:二叉树的下一个节点
- 【js版】 剑指offer【6】二叉树的下一个节点
- 【剑指offer】面试题 8:二叉树的下一个节点
- 剑指offer-二叉树的下一个节点
- 剑指offer——二叉树的下一个节点
- 剑指offer_二叉树的下一个节点
- 剑指Offer--二叉树的下一个节点
- 【剑指offer】二叉树的下一个节点
- 剑指offer(60):二叉树的下一个节点
- <剑指offer 面试题8>二叉树的下一个节点(Java)
- 剑指offer——二叉树的下一个节点___
- 找出二叉树中序遍历的所求节点的下一个节点
- 剑指offer之二叉树的下一个节点
- 剑指offer 58 - 二叉树的下一个节点
- 剑指offer --- 二叉树的下一个节点
- 剑指Offer-8:二叉树的下一个节点
- 剑指Offer--删除链表中重复的节点