[Surface] to prove safety offer a next node of a binary tree questions 08-

topic

Given a binary tree and a node which, find the next node in a preorder traversal order and returns. Note that the node in the tree contains only about the child nodes, the parent node contains a pointer pointing to.

1. Ideas

def: specified node is pNode; next node traversal sequence order is res
(. 1) if pNode have the right subtree, then the right subtree then pNode in res there must
law traversal sequence in accordance with,
① the right if pNode of subtree the left subtree, then the res there must be a logical position of the left subtree so pNode right subtree of the left-most node, so that only the while loop looking down on it;
② if pNode right subtree no left subtree , then res is pNode.right;
(2) if pNode no right subtree, then back up along pNode.next, there are two cases
①res.next.left == res, at this time need to return res.next
②res.next .left! = res, continue to back up, until the condition (2) ①, or can not meet, it means that there is no next node pNode.

2. Code (Java)

// 二叉树节点类
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) {
		if (pNode == null) {
			return null;
		}
		// pNode存在,其实按照题目要求pNode一定合法存在的
		TreeLinkNode res = pNode;
		if (res .right != null) {
			res = res.right;
			while (res.left != null) {
				res= res.left;
			}
			return res;
		} else if (res.right == null) {
			while (res.next != null) {
				if (res.next.left == res)
					return res.next;
				res = res.next;
			}
		}
		return null;
	}
}

ps: do question the very beginning, when the idea was wrong, understood to need help to solve preorder the answer, but not the subject of argument in the original tree, this line of thought obviously wrong, consider the complex. Direct use of the characteristics described in the title of the binary tree, in particular also its next pointer to a parent node which can be answered.

Published 13 original articles · won praise 9 · views 115

Guess you like

Origin blog.csdn.net/flower_48237/article/details/104072651