Brush offer to prove safety issues Summary - Tree Part (b)

Stars: 1

And a path for the binary value 1

【topic】

An input binary tree root node and an integer, the binary print values ​​of nodes in the input path and all integers. Forming a path to the path definition begins from the root node of the tree down to the leaf node has been traversed nodes.

[Code]


	/**
     * 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
     * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
     * (注意:在返回值的 list 中,数组长度大的数组靠前)
     *
     * 思路:
     * 保存所有路径,并把路径长度放在首位,然后在进行删除和排序
     * 经过测试,上面这种方式不可行,因为需要递归的结果来循环找从叶子节点的序列,
     * 但是递归返回的ArrayList是不断变化的,而ArrayList对于变化的序列是不可操作的
     * 会抛出并发修改异常
     *
     * 这种不可行的方式是从下往上回溯,需要遍历叶子节点,在添加根节点
     * 那么,从根节点往叶子节点的上到下的回溯方式,不需要遍历
     *
     * 思路2:
     * 可以对target进行操作,每次减去root的val,对target==0以及是否到达叶子节点判断
     *
     * 补充:
     * 对于这种返回值的递归,需要与跳出条件进行区分,
     * 输入值为空和递归的跳出条件,如果不一致,通常需要另起一个方法
     * */
	
	ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
    ArrayList<Integer> path = new ArrayList<>();

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if (root == null || target == 0) return new ArrayList<>();

        Find(root,target,paths,path);

        return paths;
    }

    /**
     * 回溯的思想,
     * 通过递归,把不正确的值还原
     * */
    public void Find(TreeNode root, int target,
                     ArrayList<ArrayList<Integer>> paths, ArrayList<Integer> path) {

        if (root == null) return;

        // 创建path的副本,并且把root加入其中
        path.add(root.val);
        target -= root.val;

        // 不符合条件
        if (target < 0) return;

        // 到达叶子节点并且target符合
        if (target == 0 && root.left == null && root.right == null) {
            // 找到一条符合条件的路径并返回
            paths.add(path);
            return;
        }

        Find(root.left,target,paths,new ArrayList<>(path));
        Find(root.right,target,paths,new ArrayList<>(path));
    }

[Thinking]

  • Save all paths, and the path length in the first place, and then conducting delete and sort
    tested above this way it is not possible, because the results need to be recursive loop sequence from the leaf nodes to find,
    but recursive returned ArrayList is constantly changing , and ArrayList sequence changes for inoperable
    throw exception concurrent modification

  • This approach is not feasible to back up from the bottom, need to traverse leaf node, add the root node
    , then, way back from the root node to the leaf node to the next, and not need to traverse

  • Ideas 2:
    can operate on the target, each of subtracting val root, and a determination of whether the target == 0 reaches a leaf node

  • NOTE:
    For the recursive return this value, it is necessary to distinguish exit conditions,
    the input value is empty and the recursion out condition, and if not, usually require a method other from

  • Supplement 2:
    Multipath save for this arraylist, arraylist can be passed in an existing constructor is equivalent to deep copy.


2. binary search trees and doubly-linked list

【topic】

Enter a binary search tree, the binary search tree converted into a doubly linked list sorted. Requirements can not create any new node, point to only adjust the tree node pointer.

[Code]

public TreeNode Convert(TreeNode pRootOfTree) {

        if (pRootOfTree == null) return null;

        if (pRootOfTree.left == null && pRootOfTree.right == null)
            return pRootOfTree;

        TreeNode left,right,temp;

        left = Convert(pRootOfTree.left);
        right = Convert(pRootOfTree.right);

        // 右节点不为空
        if (right != null) {
            pRootOfTree.right = right;
            right.left = pRootOfTree;
        }

        if (left == null) {
            return pRootOfTree;
        } else {
            temp = left;
            while (temp.right != null) temp = temp.right;

            temp.right = pRootOfTree;
            pRootOfTree.left = temp;

            return left;
        }

    }

[Thinking]

Note that the case of which the return is empty, when connecting the left and right subtrees, it is necessary to consider whether there is a left and right subtrees.

3. binary tree of depth

【topic】

Input binary tree, find the depth of the tree. Forming a path tree from the root node to the leaf node sequentially passes (including the root, leaf nodes), the depth of the length of the longest path in the tree.

[Code]

	/**
     *
     * 输入一棵二叉树,求该树的深度。
     * 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,
     * 最长路径的长度为树的深度。
     * */
    public int TreeDepth(TreeNode root) {
        if (root == null) return 0;

        int left,right,high;

        left = TreeDepth(root.left);
        right = TreeDepth(root.right);

        high = left > right ? left : right;

        return high + 1;
    }

[Thinking]

Non-recursive implementation:

  • With a queue of hierarchical binary tree traversal;
  • In the hierarchy traversal process, every time when a certain layer queue node after the completion of the team, H + 1;
  • The key point: what distinguish one node of a queue out the team finished the criteria?
    Prior to dequeue the queue at this time only a recording layer node, the size of the queue is the number of nodes in a layer. When this number reaches zero, then all of the layer node to complete the dequeue

4. balanced binary tree

【topic】

Input binary tree, the binary tree is determined whether a balanced binary tree.

[Code]

	/**
     *
     * 输入一棵二叉树,求该树的深度。
     * 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,
     * 最长路径的长度为树的深度。
     * */
    public int TreeDepth(TreeNode root) {
        if (root == null) return 0;

        int left,right,high;

        left = TreeDepth(root.left);
        right = TreeDepth(root.right);

        high = left > right ? left : right;

        return high + 1;
    }

    /**
     * 平衡二叉树:
     * 1.空树或者左右子树高度差不超过1
     * 2.左右子树也是平衡二叉树
     * */
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null) return true;

        int left,right,minus;

        left = TreeDepth(root.left);
        right = TreeDepth(root.right);
        minus = left - right;

        if (minus<=1 && minus>=-1) {
            return IsBalanced_Solution(root.left)
                    && IsBalanced_Solution(root.right);
        } else {
            return false;
        }
    }

The next node binary tree

【topic】

And wherein a given binary tree of a node, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to.

[Code]

    /**
     * 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
     * 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
     *
     * 方法1:
     * 根据给定的节点,找到该二叉树的根节点
     * 在根据根节点进行中序遍历,然后获取下一个节点
     * */
    ArrayList<TreeLinkNode> path;
    public TreeLinkNode GetNext(TreeLinkNode pNode) {

        if (pNode == null) return null;

        TreeLinkNode root,res;

        root = pNode;
        while (root.next != null) {
            root = root.next;
        }
        path = new ArrayList<>();
        FindPath(root);

        int tar,i;
        tar = pNode.val;
        res = null;
        for (i=0; i<path.size(); i++) {
            if (path.get(i).val == tar) {
                if ((i+1) < path.size()) {
                    res = path.get(i+1);
                }
                break;
            }
        }
        return res;
    }

    public void FindPath(TreeLinkNode root) {
        if (root == null) return;

        if (root.left == null && root.right == null) {
            path.add(root);
            return;
        }

        FindPath(root.left);
        path.add(root);
        FindPath(root.right);
    }

[Thinking]

The above solution is not necessary to consider a variety of special situations

Here Insert Picture Description

Careful observation, in order to be classified as a next node types:

  • A right subtree, the next node is the leftmost node in the right subtree, such as B, is the next node H

  • No right subtree, the nodes and the node is the parent node of the left subtree, then the next node is the parent node of the node, for example, H, is next node E

  • No right sub-tree, and the node is the junction point of the right subtree of the parent node, then we have been traced along a parent node until it finds a node is the parent node of the left subtree, if there node, then the node's parent node is what we are looking for the next node. For example I, the next node is A; G example, and the node does not meet the situation, so there is no next node G

He published 196 original articles · won praise 878 · Views 300,000 +

Guess you like

Origin blog.csdn.net/qq_33945246/article/details/104512273