zoukankan      html  css  js  c++  java
  • 带parent指针的successor求解

    题目:

      给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点(不存在重复数据)。树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

        

    思路:

      如果当前节点有右孩子,则下一个节点是右孩子中最左子节点。如果当前节点是其父节点的左子节点,则下一个节点就是父节点(节点没有右孩子)。如果当前节点是父节点的右子节点(节点没有右孩子),下一个节点:父节点是其父节点的左孩子。最后没找到的话 就说明这是最后一个,不存在他的下一个了。

    代码:

    /*有parent的解法*/
    public class Successor0 {
        public TreeNode<Integer> findSuccessor(TreeNode<Integer> node) {
            if (node == null)
                return null;
            if (null != node.right) {
                return minOfRight(node.right);
            } else {
                TreeNode<Integer> p = node;
                while (p.parent != null && p == p.parent.right) {
                    p = p.parent;
                }
                return p.parent;
            }
        }
    
        private TreeNode<Integer> minOfRight(TreeNode<Integer> right) {
            TreeNode<Integer> p = right;
            while (p.left != null)
                p = p.left;
            return p;
        }
    
        public static class TreeNode<T> {
    
            public T val;
            public TreeNode<T> left = null;
            public TreeNode<T> right = null;
            public TreeNode<T> parent = null;
    
            public TreeNode(T val) {
                this.val = val;
            }
    
        }
    }
  • 相关阅读:
    routine 程序;日常工作|日常的;例行的
    have great expectation of 寄予厚望
    数据库总结十完整性约束
    Spoken Language One
    Stature 身高,身材;(精神、道德等的)高度
    ultimate与estimate
    dramatically 从戏剧角度;戏剧性地,显著地
    predestined 注定的
    How to lists.
    endanger 危及;使遭到危险
  • 原文地址:https://www.cnblogs.com/xiaoyh/p/10408427.html
Copyright © 2011-2022 走看看