剑指offer——二叉树的下一个节点

我的代码实现:

/*
struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};
*/
class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode)
    {
        TreeLinkNode* currNode;
        //case one: The node has right son
        if(pNode->right != NULL){
            currNode = pNode->right;
            while(currNode->left){
                currNode = currNode->left;
            }
            return currNode;
        }
        //case two: The node does not has right son, it is the left son of its father
        if(pNode->next == NULL)
            return NULL;
        if(pNode == pNode->next->left){
            return pNode->next;
        }
        //case two: The node does not has right son, it is the right son of its father
        if(pNode == pNode->next->right){
            currNode = pNode->next;
            while(currNode->next != NULL &&currNode != currNode->next->left){
                currNode = currNode->next;
            }
            return currNode->next;
        }
        return NULL;
    }
};

下面是转载的文章

原文地址:https://blog.csdn.net/sbq63683210/article/details/51839408

题目描述:

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。


思路:

根据中序遍历的特点,要找到一个节点的下一个节点无非就是三种情况:1、有右子树,这时只需要把其右孩子作为下一个遍历的(并不是要找的)节点,然后沿着该节点的左子树(如果有的话)出发,直到遇到叶子节点,那么该叶子节点就是其下一个要找的节点;2、没有右子树,则判断该节点是否是其父节点的左孩子,如果是则其下一个要找的节点是其父节点;3、如果不是其父节点的左孩子,则把其父节点作为下一个遍历的节点,向上回溯,直到找到父节点没有父节点并且父节点是父节点的父节点的左孩子为止。综合这三种情况就可以找到二叉树中任意一个节点的下一个节点。


代码实现:

public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        TreeLinkNode curNode = null;
        //第一步:判断是否有右孩子
        if(pNode.right != null){
            curNode = pNode.right;
            while(curNode.left != null) curNode = curNode.left;
            return curNode;
        }
        //第二步:判断是否是其父节点的左孩子
        if(pNode.next == null) return null;
        if(pNode == pNode.next.left){
            return pNode.next;
        }
        //第三步:向上找其父节点,直到父节点是其父节点的父节点的左孩子
        curNode = pNode.next;
        while(curNode.next != null){
            if(curNode == curNode.next.left){
                return curNode.next;
            }
            //继续向上找父节点
            curNode = curNode.next;
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/ljh0302/article/details/80661737