面试题:遍历三颗相连的满二叉树

题目:三颗满二叉树,他们的根节点互为父节点,从任意节点遍历整颗二叉树

要求:不能使用外部变量、集合等

不能改变树结构

不能 给节点添加额外属性

ps: 屁事真多

思路:一颗没毛病,就前序遍历就OK, 三颗也一样,但是要考虑到遍历根节点时死循环问题,方式为:如果一个节点是根节点,则设置标识, 并且只记录第一次碰到的的根节点, 还有一点,递归时要传过去当前节点,防止重复遍历

  1. 打印
  2. 遍历头
  3. 遍历左孩子
  4. 遍历右孩子
java 复制代码
static class Node<E> {
    E v;
    Node<E> left;
    Node<E> right;
    Node<E> head;

    public Node(E v) {
        this.v = v;
    }
}


/**
 * @param node
 * @param sourceNode 遍历到node节点的节点
 * @param firstRootNode 第一次碰到的根节点
 */
private static void threeTreeTraversal(Node<Integer> node, Node<Integer> sourceNode, Node<Integer> firstRootNode) {

    if (null == node) {
        return;
    }
    // 先打印本节点值
    System.out.print(node.v + " ");

    // 如果一个节点是根节点,则设置标识,方式root节点之间死循环, 并且只记录第一次的根节点
    if (isRoot(node) && null == firstRootNode) {
        firstRootNode = node;
    }
    if (node.head != sourceNode && node.head != firstRootNode) {
        // 遍历头节点
        threeTreeTraversal(node.head, node, firstRootNode);
    }

    if (node.left != sourceNode) {
        // 遍历左子树
        threeTreeTraversal(node.left, node, firstRootNode);
    }

    if (node.right != sourceNode) {
        // 遍历右子树
        threeTreeTraversal(node.right, node, firstRootNode);
    }
}

public static boolean isRoot(Node<Integer> node) {
    Node<Integer> parent = node.head;
    if (parent.left == node || parent.right == node) {
        return false;
    }
    return true;
}
相关推荐
月明长歌1 天前
【码道初阶】【LeetCode 572】另一棵树的子树:当“递归”遇上“递归”
算法·leetcode·职场和发展
月明长歌1 天前
【码道初阶】【LeetCode 150】逆波兰表达式求值:为什么栈是它的最佳拍档?
java·数据结构·算法·leetcode·后缀表达式
C雨后彩虹1 天前
最大数字问题
java·数据结构·算法·华为·面试
java修仙传1 天前
力扣hot100:搜索二维矩阵
算法·leetcode·矩阵
浅川.251 天前
xtuoj 字符串计数
算法
天`南1 天前
【群智能算法改进】一种改进的金豺优化算法IGJO[1](动态折射反向学习、黄金正弦策略、自适应能量因子)【Matlab代码#94】
学习·算法·matlab
Han.miracle1 天前
数据结构与算法--006 和为s的两个数字(easy)
java·数据结构·算法·和为s的两个数字
AuroraWanderll1 天前
C++类和对象--访问限定符与封装-类的实例化与对象模型-this指针(二)
c语言·开发语言·数据结构·c++·算法
月明长歌1 天前
【码道初阶】LeetCode 622:设计循环队列:警惕 Rear() 方法中的“幽灵数据”陷阱
java·算法·leetcode·职场和发展
Dylan的码园1 天前
链表与LinkedList
java·数据结构·链表